2012-04-30 46 views
0
Scanner input = new Scanner(System.in); 
System.out.println("Input the minimum necessary word count in a single article!"); 
int minArticleLength1 = input.nextInt(); 
while (minArticleLength1<0){ 
    System.out.println("Input the minimum necessary word count in a single article!"); 
    minArticleLength1 = input.nextInt(); 
} 

正如你在程序的這部分看到的,你需要給int類型變量賦值。一切工作正常,如果我輸入int類型的值,但是如果我分配一個值像1.1程序啓動一個無限循環,直到我停止它。我應該在代碼中更改以使程序不接受double值,即使int是必需的,以便如果我要輸入像1.1那樣的double值,程序會要求再次輸入值。當程序需要int時,保持程序不接受double值

回答

2

您可以在循環中使用try...catch語句來捕獲無效輸入。

while (minArticleLength1 < 0){ 
    System.out.println("Input the minimum necessary word count in a single article!"); 
    try { 
     minArticleLength1 = input.nextInt(); 
    } catch (InputMismatchException imex) } 
     System.out.println("Please enter a valid integer."); 
     minArticleLength1.nextLine(); 
    } 
}