如何使程序在for循环内等待用户输入?

问题描述:

我的程序需要获取有关用户输入车辆数量的信息。我使用了一个for循环来让它运行这个数量,但是当要求提供这些信息时,程序将运行整个过程并且不会停止供用户输入。这里是我的代码:如何使程序在for循环内等待用户输入?

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(); 
    } 
} 

}

您需要添加额外的scan.nextLine(),以消耗\n字符scan.nextInt()没有消耗:

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

非常感谢,现在工作:) – 2014-11-14 17:24:00

+1

@AdenPeerrson然后接受他的回答:) – yts 2014-11-14 17:47:54

另一种方式来解决这个问题“nextInt”函数的问题是解析一个“nextLine”输入到Int类型

尝试int x = Integer.parseInt(scan.nextLine());而不是int x = scan.nextInt();