在扫描仪读取输入之前,必须多次键入 [英] Must type multiple times, before scanner reads input

查看:41
本文介绍了在扫描仪读取输入之前,必须多次键入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我运行这段代码

Scanner sc = new Scanner();
while (true) {
        if (sc.next().equals("1"))
            System.out.println("--1--");

        else if (sc.next().equals("2"))
            System.out.println("--2--");

        else if (sc.next().equals("3"))
            System.out.println("--3--");

        else if (sc.next().equals("4"))
            System.out.println("--4--");

        else if (sc.next().equals("help"))
            System.out.println("--help--");
    }

我第一次输入enter时不会读取.在读取输入之前,我必须键入2-4次.一个会话可能看起来像这样:

It will not read the first time I type enter. I have to type 2-4 times before it reads the input. A session could look like this:

1
1
1
1
--1--
3
3
--3--
help
2
1
help
--help--

无论我键入什么内容,它都只会读取四个输入中的最后一个输入. 有时它是在两次输入后读取的.我对此很困惑. 我应该改为使用多个扫描仪吗?

No matter what I type, it will only read the last input of the four inputs. Sometimes it reads after two inputs. I'm really confused about this. Should I instead use multiple scanners?

推荐答案

您的概念在这里是错误的.

Your concepts are wrong here.

每次您要求输入sc.next()时,它将等待输入.如果该输入等于您想要的输入,那么将执行代码.

Each time you ask for sc.next() it will wait for the input. If that input is equal to what you want it to be, then the code is executed.

您可以通过将sc.next()存储在String变量中,然后进行比较来更正此问题.

You can correct this by storing sc.next() in a String variable, and then comparing it.

此处: if (sc.next().equals("1")) 它要求输入.

Here: if (sc.next().equals("1")) it asks for an input.

如果该输入为1,则将执行代码并打印出--1--.否则,它跳转至:if (sc.next().equals("2")).现在,如果输入为2,则将执行打印--2--的代码.否则,它会跳转到if (sc.next().equals("3")),依此类推.

If that input is 1 then the code is executed and --1-- is printed out. Else, it jumps to this: if (sc.next().equals("2")). Now if the input is 2 then the code to print --2-- is executed. Else, it jumps to if (sc.next().equals("3")) and so on.

您可以通过以下方式纠正此问题:

You can correct this by:

  • sc.next()存储在String变量中,然后进行比较.
  • 使用开关盒模块比较输入.
  • storing sc.next() in a String variable, and then comparing it.
  • using a switch-case block to compare the input.

这篇关于在扫描仪读取输入之前,必须多次键入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆