2017-11-03 82 views
-2

我試圖要求用戶輸入兩個數字。我想檢查這些輸入是否實際上是數字,但是如果第一個輸入是字符串,我迄今爲止的代碼不會讓我輸入第二個值。掃描儀不讀取其他語句中的輸入

因此,掃描儀不會讀取任何else語句。

我怎麼能使它工作?

import java.util.Scanner; 

public class calculations { 
    public static void main(String[] args) { 
     Scanner console = new Scanner(System.in); 
     System.out.print("Please enter your first name: "); 
     String fname = console.nextLine(); 
     System.out.print("Please enter your last name: "); 
     String lname = console.nextLine(); 
     System.out.print("Please enter your first number: "); 
     if (console.hasNextInt()) { 
      int number1 = console.nextInt(); 
      System.out.print("Please enter your second number: "); 
      if (console.hasNextInt()) { 
       int number2 = console.nextInt(); 
      } 
     } else 
      System.out.print("Please enter your second number: "); 
     if (console.hasNextInt()) { 
      int number2 = console.nextInt(); 
      // this part does not work 
     } 
    } 
} 
+2

您的'else'塊只包含一個打印語句。 –

+1

添加到以前的評論中,將'else'條件放在'{}'塊中應該有所幫助。 – Eugene

+0

我已經試過了。可悲的是,這並沒有幫助。任何其他想法? – kiaora

回答

1

你只需要你的else聲明後添加console.nextLine();,因爲Scanner.hasNextInt方法不將光標移動過去你以前的輸入(如果它是一個字符串)。

+1

OP永遠不會調用nextInt()。你提到的問題不在於此。它是關於nextLine()讀取空字符串的,因爲nextInt()不會使用EOL。調用next()將是這個問題的錯誤解決方案,但這個問題在這裏不會發生。 –

+0

@JB Nizet,你是​​對的,問題不在於消費EOL。但是,用next()方法移動光標似乎是一個有效的解決方案,所以我編輯了答案。感謝您指出! – Eugene

+1

如果「請輸入您的第一個數字:」的答案是「Hello world」,並且您調用next()來移動光標,那麼光標在哪裏?它應該在哪裏? –