【问题标题】:Why Wont My Java Scanner Take In input?为什么我的 Java 扫描程序无法接收输入?
【发布时间】:2015-05-09 07:58:56
【问题描述】:
package Lessons;

import java.util.Scanner;

public class Math {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.print("please enter the first number of your question! ");
        int a1 = s.nextInt();
        System.out.print("So you chose " + a1);
        System.out.println(" Choose ur second number");
        int a2 = s.nextInt();
        System.out.print("You chose " + a2 + " for your second number");
        System.out.print(" Now enter ur operator ");
        String b1 = s.nextLine();
        if (b1.equalsIgnoreCase("-")) {
            System.out.println("You chose " + b1 + "as ur operator");
        }
    }

}

我不明白为什么第 15 行不接受任何输入,任何帮助将不胜感激:3

输出

请输入您的问题的第一个数字! 2552 所以你选择了2552 选择你的第二个号码 41 你选择了 41 作为你的第二个号码 现在 输入你的运营商

由于某种原因,输出在最后一行结束并停止,不带任何信息!

【问题讨论】:

  • 你能发布你的输出吗?

标签: java


【解决方案1】:

您需要在调用in.nextInt() 的行之后立即调用in.nextLine() 原因是只要求下一个整数不会消耗输入中的整行,因此您需要跳到下一个通过调用 in.nextLine() 在输入中的换行符。

int a2 = s.nextInt();
s.nextLine();

这几乎必须在每次调用不消耗整行的方法后需要换行时完成,例如当您调用nextBoolean() 等时。

【讨论】:

  • 我用一个字符串做这个,我试图接受不是一个 int :)
  • @Phoenix 请重新阅读我的回答,这是您问题的解决方案。
  • 我会在我的 5 分钟结束后 ;)
【解决方案2】:

调用s.nextInt() 会读取下一个int,但不会读取之后的换行符。所以新行将在第 15 行读取。如果您确定每个输入都将放在单独的行中,那么您可以通过在第 15 行之前添加一个额外的 s.nextLine() 来解决此问题:

...
System.out.print(" Now enter ur operator ");
s.nextLine();
String b1 = s.nextLine();
...

【讨论】:

    【解决方案3】:

    在接受字符串输入的部分试试这个。

    `System.out.print(" Now enter ur operator ");
        String b1 =s.next();
        if (b1.equalsIgnoreCase("-")) {
            System.out.println("You chose " + b1 + "as ur operator");
    }`
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多