2014-02-19 197 views
3

我是一個noob,所以如果我問一個愚蠢的問題,我很抱歉。我要求用戶輸入一個數字值。如果該值小於12,或者非數字值(例如數字),我希望它提示他們輸入另一個值。當輸入的值至少爲12時,我希望將該值分配給名爲creditUnits的變量;使用Java驗證輸入

當我詢問最初的提示時,如果輸入的值不是數字,我的程序會捕獲它,它會要求用戶輸入一個有效的數字:「。 while循環似乎很好。

我遇到了第二個循環的問題,它應該捕獲輸入的數字小於12的任何數字。它會要求用戶輸入一個大於11的值。問題是我有在這一點上,如果用戶在這一點上輸入任何值,程序就在那裏。任何幫助,將不勝感激,我提前爲我的代碼的草率道歉:

System.out.print("Enter the credits's you will take each term: "); 

while (!in.hasNextDouble()){ 
    System.out.print("Enter a valid number: "); 
    in.next(); 
} 

creditUnits = in.nextDouble(); 

if (creditUnits < 12){ 
    System.out.print("Enter a number greater than 11: "); 
    in.next(); 
} 

creditUnits = in.nextDouble();      
System.out.println("You will be taking " + creditUnits + " credits per term.");  
+3

有沒有愚蠢的問題。 –

+0

嘗試用'hasNextInt()'替換'hasNextDouble()'。順便說一下,我同意Secator:沒有愚蠢的問題;具體而言,你的問題根本不愚蠢;) – Barranka

+0

user3330001對我的回答有幫助嗎? –

回答

4

這是因爲你問掃描儀搶下兩個輸入端,當你只想要第一個。

System.out.print("Enter the credits's you will take each term: "); 

while (!in.hasNextDouble()){ 
    System.out.print("Enter a valid number: "); 
    in.next(); 
} 

creditUnits = in.nextDouble(); 

if (creditUnits < 12){ 
     System.out.print("Enter a number greater than 11: "); 
     creditUnits = in.nextDouble(); 
} 


System.out.println("You will be taking " + creditUnits + " credits per term.") 

此外,有一件事你應該考慮的是把if(creditUnits < 12)塊在一個while循環,這樣就可以不斷地檢查,如果他們進入了一個數大於12

喜歡的東西:

System.out.print("Enter the credits's you will take each term: "); 
while (true){ 
    System.out.print("Enter a valid number: "); 
    creditUnits = in.nextDouble(); 
    if (creditUnits < 12){ 
     System.out.print("\nNumber must be greater than 12!\n"); 
    }else 
     break; 
} 

System.out.println("You will be taking " + creditUnits + " credits per term."); 

此外,沒有這樣的事情作爲一個愚蠢的問題。只有愚蠢的傳單粉絲。 /笑話

0

像四面楚歌的斯格表示,

if (creditUnits < 12){ 
    System.out.print("Enter a number greater than 11: "); 
    in.next(); 
} 

的in.next()有折騰掉你進入掃描儀,然後塊如果只是直到它得到一個雙在這裏你輸入空格:

creditUnits = in.nextDouble(); 

如果你輸入任何東西,除了在空白(我假設你只是按下回車鍵),那麼它會打印出「你會考慮......」的一部分,如果它是一個有效的兩倍。否則,它會拋出InputMismatchException。

你可能會更好過接收輸入和手動應用的有效性檢查,而不是循環nextDouble

public static void main(String[] args) throws IOException { 
    System.out.print("Enter the credits you will take each term: "); 

    Scanner in = new Scanner(System.in); 
    String input = in.next(); 

    double credits = 0.0; 

    while (true) { 
     try { 
      credits = Double.parseDouble(input); 
      if (credits < 12.0) { 
       throw new IllegalArgumentException("Must take at least 12 credits."); 
      } else { 
       break; 
      } 
     } catch(IllegalArgumentException e) { 
      System.out.print("Enter a number greater than 11: "); 
      input = in.next(); 
     } 
    } 

    System.out.println("You will be taking " + credits + " credits per term."); 
    in.close(); 
}