2017-11-03 84 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()来移动光标,那么光标在哪里?它应该在哪里? –