Java扫描仪要求输入循环

发布于 2025-01-25 10:24:20 字数 536 浏览 2 评论 0原文

因此,我有这个程序:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
       
        Scanner scan = new Scanner(System.in);
        String name = "";
        while(name.isBlank()) {
            System.out.println("Enter your name: ");
            name = scan.next();     
        }
        System.out.println("Hello "+ name + "!");
    }
}

该程序应该提示用户输入其名称。并且应该继续提示他们直到他们实际输入名称为止,这意味着如果他们将输入字段保持空白并按Enter,则将再次提示。但是,该程序没有这样做。即使我在不​​输入我的名字的情况下按Enter,该程序也会冻结,并且不会再次提示。

So I have this program:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
       
        Scanner scan = new Scanner(System.in);
        String name = "";
        while(name.isBlank()) {
            System.out.println("Enter your name: ");
            name = scan.next();     
        }
        System.out.println("Hello "+ name + "!");
    }
}

This program is supposed to prompt the user to enter their name. And it is supposed to keep prompting them until they actually enter their name, meaning that if they keep the input field blank and press enter, they will get prompted again. However, this program does not do that. Even if I press ENTER without entering my name, the program just freezes and doesn't prompt again.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

追星践月 2025-02-01 10:24:20

您应该使用nextline()而不是next()用于您要实现的行为。

documentation>

扫描仪使用定界符模式打破了对令牌的输入,默认情况下,该模式与空格匹配。

next():从此扫描仪查找并返回下一个完整的令牌。

nextline():将此扫描仪超越当前行并返回跳过的输入。

next()方法一旦遇到一个空白,就会中断其读取,例如:一个选项卡(\ t),line feed(\ n),托架返回(\ r)或适当的空间(还有其他字符属于 White Space 定义)。当您在输入开头键入空间或新线时,scanner期望使用next()调用 call,您的scanner 实例将简单地忽略它,因为尚未键入“什么都没有”(除了一个分隔符,返回值未包含)。

另一方面,当您调用nextline()方法时,此方法将返回当前行或当前行的其余部分,具体取决于内部scanner剩下的s光标,不包括末尾的任何线分隔符。因此,每当您输入nextline()期望输入时,每次输入时,这将返回一个空字符串,而不是next()< /代码>方法,它将阻止直到输入一些正确的输入和分离器。

这是您的代码的调整版本:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String name = "";
    while (name.isBlank()) {
        System.out.print("Enter your name: ");
        name = scan.nextLine();
    }
    System.out.println("Hello " + name + "!");
}

You should use nextLine() rather than next() for the behavior you're trying to achieve.

As the documentation states:

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

next(): Finds and returns the next complete token from this scanner.

nextLine(): Advances this scanner past the current line and returns the input that was skipped.

The next() method interrupts its read once it encounters a white space, for example: a tab (\t), a line feed (\n), a carriage return (\r) or a proper space (there are also other characters which fall into the white space definition). When you keep typing a space or a new line at the beginning of your input while your Scanner is expecting something with a next() call, your Scanner instance will simply ignore it as "nothing" has been typed yet (nothing but a separator, which is not included in the returned value).

On the other hand, when you're invoking the nextLine() method, this one returns the current line, or the rest of the current line depending on where the internal Scanners cursor was left, excluding any line separator at the end. So, every time you're typing enter when a nextLine() is expecting an input, this will return an empty String as opposed to the next() method, which would block until some proper input and a separator have been entered.

Here is the tweaked version of your code:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String name = "";
    while (name.isBlank()) {
        System.out.print("Enter your name: ");
        name = scan.nextLine();
    }
    System.out.println("Hello " + name + "!");
}
街角卖回忆 2025-02-01 10:24:20

我想补充丹的回答。这里的关键是next()指示的文档。

此方法在等待输入扫描

时可能会阻止

问题,这是什么意思?这意味着OP的代码按应有的方式工作。

Enter your name: 
[ENTER pressed]
[ENTER pressed]
[ENTER pressed]
[ENTER pressed]
[ENTER pressed]
hector
Hello hector!

由于按Enter被按下没有输入,因此呼叫next()方法块等待输入。输入后,消耗了扫描仪输入并产生适当的输出。因为该方法正在阻止,所以没有循环发生。因此,将代码冻结在不冻结时的外观。

I would like to supplement Dan's answer. The key here is what the documentation for next() indicates.

This method may block while waiting for input to scan

The question is, what does this mean? It means the OP's code works the way it is supposed to.

Enter your name: 
[ENTER pressed]
[ENTER pressed]
[ENTER pressed]
[ENTER pressed]
[ENTER pressed]
hector
Hello hector!

Because there was no input when ENTER was pressed, the call to next() method blocks waiting for input. Once input is entered, the scanner input is consumed and the proper output is produced. Because the method is blocking, no looping occurs; thus giving the appearance that the code is frozen when it is not.

等待我真够勒 2025-02-01 10:24:20

在您的代码中,您使用了next()进行用户输入的方法。实际next()当您不希望输入字符串为空时使用。因此,如果您要在输入非空的内容之前按Enter,next()期望任何非空字符串(等待非空字符串),而忽略了以前输入的所有空格字符。

对于您的情况,如果名称为空,则需要提示。在这种情况下,您需要使用nextline()方法,如果用户按Enters,它将移至下一个语句。然后检查循环时内部的条件。

注意:next()仅接受单词时nextline()接受多个单词。

正确的代码是@Dan在答案中提供的。

In your code you have used next() method to take the user input. Actually next() is used when you do not want the input string to be empty. So, if you are pressing enter before entering something non-empty, next() is expecting any non-empty string(waiting for the non-empty string) and neglecting all the whitespace characters entered before.

For your case you want to prompt after every enter if the name is empty. In this case you need to use nextLine() method instead, it will move to the next statement if the user presses enter. And then the condition inside while loop is checked.

Note: next() only accepts single word while nextLine() accepts multiple words.

The correct code is what @Dan has provided in his answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文