简体   繁体   中英

How to make the program wait for user input when it's inside a for loop?

my program needs to get information about a user inputted amount of cars. I used a for loop to make it run for that amount, but when it comes to asking for the information, the program will run the whole thing and will not stop for the user to input. Here is my code:

public class Main {
public static void main(String[] args) {
    SimpleDateFormat format = new SimpleDateFormat("HH:MM:SS");

    final int distance = 1609;

    Scanner scan = new Scanner(System.in); 

    System.out.println("How many cars entered the gate?");
    int x = scan.nextInt();

    for (int c = 0; c < x; c++) {
        System.out.println("Please input the time the car entered the zone: (HH:MM:SS)");
        String start = scan.nextLine();
        System.out.println("Please input the time the vehicle left the zone: (HH:MM:SS)");
        String stop = scan.nextLine();
    }
}

}

You need to add an extra scan.nextLine() , in order to consume \\n character that scan.nextInt() didn't consume:

int x = scan.nextInt();
scan.nextLine(); // consume the newline character

Another way to solve this issue with "nextInt" function is parsing a "nextLine" input to Int type

try int x = Integer.parseInt(scan.nextLine()); instead int x = scan.nextInt();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM