2016-02-12 72 views
0

我想驗證1或2的輸入。但是,使用此代碼,如果您輸入字母,它會使程序崩潰。isDigit validation

這怎麼解決?

System.out.print("Choice: "); 
userSelection = keyboard.nextInt(); 

while (flag == 0) 
{ 
    if (userSelection == 1 || userSelection == 2) 
    { 
     flag = 1; 
    } 
    if(Character.isDigit(userSelection)) 
    { 
     flag = 1; 
    } 
    else 
    { 
     flag = 0; 
    } 
    if (flag == 0) 
    { 
     //this is a system clear screen to clear the console 
     System.out.print("\033[H\033[2J"); 
     System.out.flush(); 

     //display a warning messege that the input was invalid 
     System.out.println("Invalid Input! Try again, and please type in selection 1 or selection 2 then hit enter"); 
     System.out.print("Choice: "); 
     userSelection = keyboard.nextInt(); 
    } 
} 
+0

使用嘗試,趕上這樣,它不會破壞程序。你應該看看它在java中非常有用的文檔,你可以嘗試/捕獲一切:D –

回答

0

試試這個代碼片段:

try (Scanner scanner = new Scanner(System.in)) { 
    int choice; 
    while (true) { 
     System.out.print("Choice: "); 
     if (!scanner.hasNextInt()) { 
      scanner.nextLine();//read new line character 
      System.err.println("Not a number !"); 
      continue; // read again 
     } 
     choice = scanner.nextInt(); //got numeric value 
     if (1 != choice && 2 != choice) { 
      System.err.println("Invalid choice! Type 1 or 2 and press ENTER key."); 
      continue; //read again 
     } 
     break;//got desired value 
    } 
    System.out.printf("User Choice: %d%n", choice); 
}