2017-06-22 110 views
-2

我試圖在do-while循環內插入一個do-while循環來檢查輸入是整數。我在我想插入do-while循環的地方添加了一條評論。除了那部分,一切都很好。JAVA-驗證輸入是整數

public static void main(String[] args){ 
    int num1, num2; 
    char response; 
    Scanner in = new Scanner(System.in); 
    Scanner reader = new Scanner(System.in); 

    do {  
     System.out.print("Enter number: "); 
     num1 = in.nextInt(); 
     response = (char) reader.nextLine().charAt(0); 

     //I want to check if the input is integer here 
     do{ 
      System.out.println("Invalid input!\nPlease input integers only!"); 
     } while (response != /*something*/); 

     for(num2=0; num2 < 11; num2++) { 
      System.out.println(num1 + "X" + num2 + "=" + (num1 * num2)); 
      } 

     do { 
      System.out.println("\nDo you want to try again? [y/n]"); 
      response = (char) reader.nextLine().charAt(0); 
      if (response != 'n'&& response != 'N' && response != 'Y' && response != 'y') 
      System.out.println("Input invalid!"); 
     } while (response != 'n' && response != 'N' && response != 'y' && response != 'Y'); 

    } while (response != 'N' && response != 'n');{ 
     System.out.println("Thank you for using the table");} 
} 
+0

歡迎來到Stack Overflow!請參考https://stackoverflow.com/help/how-to-ask,特別關注相關信息(已由@StephenC編輯)。 –

+0

你可以粗體預先編碼的btw。指向某一特定行的典型方法是在代碼中發表評論,以顯示您所談論的位置。 – Carcigenicate

+0

Integer.parseInt在這裏可能會有幫助:) – Lemonov

回答

1

而不是使用一個做的,而你可以檢查使用以下方式

try{ 
    yourNumber = Integer.parseInt(yourInput); 
}catch (NumberFormatException ex) { 
    //handle exception here 
} 
0

可以用「蠻力」,並嘗試分析用戶的輸入,如果事情無效給出那麼你得到一個NumberFormatException

int num1 = 0; 
    String intCandidate = null; 
    boolean valid = false; 
    Scanner in = new Scanner(System.in); 

    while (!valid) { 
     try { 
      System.out.print("Enter number: "); 
      intCandidate = in.nextLine(); 
      num1 = Integer.parseInt(intCandidate); 
      valid = true; 
     } catch (NumberFormatException e) { 
      System.out.print("Nope... "); 
     } 
    } 
    in.close(); 
    System.out.println("Thanks!");