2013-11-01 93 views
1
import java.util.Scanner; 

public class test { 

    public static void main(String[] args) { 
     System.out.print("Enter a number: "); 
     Scanner keyboard = new Scanner(System.in); 
     int x = keyboard.nextInt(); 

    } 
} 

如何循環一段如上所述的代碼,直到輸入int而不是輸入非int時發生錯誤爲止?防止輸入錯誤

+0

開始通過查看掃描儀的Javadoc。然後嘗試一下。 –

回答

2

Scanner類有很多東西內置,所以你不需要做嘗試捕獲,除非你明確地尋找捕獲錯誤。

public static int test(){ 
    int number = 0; 
    Scanner input = new Scanner(System.in); 
    boolean valid = false; 
    do{ 
     System.out.print("Please enter an integer: "); 
     if(input.hasNextInt()){ // This checks to see if the next input is a valid **int** 
      number = input.nextInt(); 
      valid = true; 
     } 
     else{ 
      System.out.print("Not a valid integer!\n"); 
      input.next(); 
     } 
    }while(valid == false); 
    return number; 

}