2015-11-05 274 views
0

我有一個簡單的java程序,接受3個用戶輸入類型整數,雙精度和字符串。我想知道對所有這些輸入執行錯誤處理以保持程序運行的最好/最有效的方式,告知用戶他們輸入了錯誤的輸入並再次詢問他們的問題。任何幫助將不勝感激。Java用戶輸入錯誤處理

這裏是我的代碼

Scanner scan = new Scanner(System.in); 
    int inputInt; 
    double inputDbl; 
    String inputString; 


    System.out.print("Please enter a whole number: "); 
    inputInt = scan.nextInt();  
    System.out.print("Please enter a decimal number: "); 
    inputDbl = scan.nextDouble(); 
    System.out.print("Please enter a string: "); 
    inputString = scan.next().toLowerCase();  
+1

確保您使用'hasNextInt()'和'hasNextDouble()'之前調用掃描儀的方法'nextInt()','nextDouble()'。 – AndyN

+0

不要忘記接受解決問題的答案。 –

回答

1

將其拆分爲n方法,其中n是有多少用戶輸入。

對於每個用戶輸入創建獲取輸入方法:

String getStringInput(){ 
    System.out.println("Enter input"); 
    String input = scan.next(); 

    //check the input to make sure it is correct 
    if(input.equals("foo")){ 
     //if the input is incorrect tell the user and get the new input 
     System.out.println("Invalid Input"); 
     //simply return this method if the input is incorrect. 
     return getStringInput(); 
    } 

    //return the input if it is correct 
    return input; 
} 

對於獲取輸入簡單地調用該方法的主要方法:

void getAll(){ 
    String stringValue = getStringInput(); 
} 

現在,這使得它容易得到任何數量的輸入並檢查是否正確。

1
boolean validated = false; 

// this keeps user locked until he/she provides valid inputs for all variables 
while(!validated) { 
    //get inputs here 
    // .. 

    // lastly 
    validated = validateLogic(inInt, inDbl, inStr); 
} 

// keep going 

如果你想爲每個輸入單獨驗證,你shuold寫while循環3次。

0

感謝所有的輸入人,你們真棒。我選擇使用一個簡單的使用布爾觸發器的dowhile循環。我嘗試過使用try catch,但最終編寫了大量的代碼來執行非常基本的輸入檢查。所以在這裏沒有任何異常處理,我希望這不會是必要的。但願它不會對我打破

do { 
     System.out.print("Please enter a whole number: "); 
     if (scan.hasNextInt()){  
     inputInt = scan.nextInt(); 
     validInput = true; 
     } else 
      System.out.println("You have entered incorrect input! Please enter a whole number only"); 
      scan.nextLine(); 
     } while (validInput == false); 

     validInput = false; 

     do { 
     System.out.print("Please enter a decimal number: "); 
     ...... 
     ......