简体   繁体   English

虽然循环没有按预期工作。 一切似乎都是正确的。 我该如何解决这个问题?

[英]While loop is not working as expected. Everything seems to be correct. How do I fix this problem?

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.即使我在没有输入我的名字的情况下按下 ENTER,程序也只是冻结并且不会再次提示。 Please help:(.请帮忙:(。

You should use nextLine() rather than next() for the behavior you're trying to achieve.您应该使用nextLine()而不是next()来实现您想要实现的行为。

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. next() :从该扫描器中查找并返回下一个完整的标记。

nextLine() : Advances this scanner past the current line and returns the input that was skipped. nextLine() :使此扫描器前进到当前行并返回跳过的输入。

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). next()方法一旦遇到空格就会中断读取,例如:制表符 (\t)、换行符 (\n)、回车符 (\r) 或适当的空格(还有其他字符属于空白定义)。 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).当您在输入的开头继续键入一个空格或一个新行,而您的Scanner正在期待next()调用的内容时,您的Scanner实例将简单地忽略它,因为尚未键入“任何内容”(除了分隔符,这不包括在返回值中)。

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 Scanner s cursor was left, excluding any line separator at the end.另一方面,当您调用nextLine()方法时,该方法返回当前行或当前行的 rest,具体取决于内部Scanner s cursor 的剩余位置,不包括末尾的任何行分隔符。 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.因此,每次您在nextLine()需要输入时键入 enter 时,这将返回一个空String ,而不是next()方法,后者会阻塞,直到输入了一些正确的输入和分隔符。

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 + "!");
}

In your code you have used next() method to take the user input.在您的代码中,您使用了next()方法来获取用户输入。 Actually next() is used when you do not want the input string to be empty.实际上next()是在您不希望输入字符串为空时使用的。 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.因此,如果您在输入非空内容之前按回车键,则next()会期待任何非空字符串(等待非空字符串)并忽略之前输入的所有空白字符。

For your case you want to prompt after every enter if the name is empty.对于您的情况,如果name为空,您希望在每次输入后提示。 In this case you need to use nextLine() method instead, it will move to the next statement if the user presses enter.在这种情况下,您需要改用nextLine()方法,如果用户按下回车键,它将移至下一条语句。 And then the condition inside while loop is checked.然后检查 while 循环内的条件。

Note: next() only accepts single word while nextLine() accepts multiple words.注意: next()只接受单个单词,而nextLine()接受多个单词。

The correct code is what @Dan has provided in his answer.正确的代码是@Dan 在他的回答中提供的。

I would like to supplement Dan's answer.我想补充丹的回答。 The key here is what the documentation for next() indicates.这里的关键是next()的文档指示的内容。

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.这意味着 OP 的代码按照预期的方式工作。

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.因为按下 ENTER 时没有输入,所以调用next()方法会阻塞等待输入。 Once input is entered, the scanner input is consumed and the proper output is produced.输入输入后,将使用扫描仪输入并生成正确的 output。 Because the method is blocking, no looping occurs;因为该方法是阻塞的,所以不会发生循环; thus giving the appearance that the code is frozen when it is not.从而使代码看起来像是被冻结了,而实际上却没有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 合并Java中的排序无法正常工作。 尝试不使用while循环 - Merge Sort in Java not working as expected. Trying to do it without a while loop 做{}while(); 似乎没有按预期工作 - do{}while(); seems not working as expected 我如何解决这个无限的 while 循环 - How do I fix this infinite while loop Gradle 传递依赖项排除未按预期工作。 (我如何摆脱 com.google.guava:guava-jdk5:13.0 ?) - Gradle Transitive dependency exclusion is not working as expected. (How do I get rid of com.google.guava:guava-jdk5:13.0 ?) 如何在while循环中修复此计数器? - How do i fix this counter in a while loop? 尽管所有方法(似乎)都是正确的,但我的程序没有运行。 似乎是主要方法的问题? - My program doesn't run despite all methods being (seemingly) correct. seems to be a problem with the main method? 如何在 Android 中修复我的 For 循环和随机问题? - How do I fix my For loop and Random problem in Android? ArrayList在do..while循环中未按预期工作 - ArrayList not working as expected in do..while loop 如何在循环时修复我的随机数? - How do I fix my random number while loop? 为什么我在无限循环中走? 我如何解决它? - Why is my while going in a infinity loop? How do I fix it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM