2014-11-14 108 views
0

我的程序需要獲取有關用戶輸入車輛數量的信息。我使用了一個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(); 
    } 
} 

}

回答

3

您需要添加額外的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

0

另一種方式來解決這個問題「nextInt」函數的問題是解析一個「nextLine」輸入到Int類型

嘗試int x = Integer.parseInt(scan.nextLine());而不是int x = scan.nextInt();