简体   繁体   English

Java中Scanner.nextLine的问题

[英]Problems with Scanner.nextLine in Java

In Java, I have tried 在Java中,我尝试过

try (Scanner sc = new Scanner(System.in)) {
    while (sc.hasNextLine()) {
        System.out.print("Name: ");
        String name = sc.nextLine();
        System.out.println("Name is \"" + name + "\"");
    }
}

but it doesn't output Name: before asking for the input. 但在要求输入之前不会输出Name: :。

The console just shows an empty console window in which I can input the name. 控制台仅显示一个空的控制台窗口,我可以在其中输入名称。

How can I make sure Name: is outputted before asking for the name? 在要求输入名称之前,如何确保输出Name:

Edit 编辑

try (Scanner sc = new Scanner(System.in)) {
    System.out.print("Name: ");

    while (sc.hasNextLine()) {
        String name = sc.nextLine();
        System.out.println("Name is \"" + name + "\"");

        System.out.print("Age: ");
        int age = sc.nextInt();
        System.out.println("Age is " + age);

        System.out.print("Name: ");
    }

Put your println before the while loop and then add one at the end. 将您的println放在while循环之前 ,然后在末尾添加一个。

try (Scanner sc = new Scanner(System.in)) {
    System.out.print("Name: ");        
    while (sc.hasNextLine()) {

        String name = sc.nextLine();
        System.out.println("Name is \"" + name + "\"");
        System.out.print("Name: ");
    }
}

The scanner waits until it receives input before it runs the next code so just put the print before the scanner and then at the end of the while loop. 扫描程序会等到收到输入后再运行下一个代码,因此只需将打印内容放在扫描程序之前,然后放在while循环的末尾即可。

You should put System.out.print("Name: "); 您应该将System.out.print("Name: "); before of the while loop like this: 在while循环之前,如下所示:

  try (Scanner sc = new Scanner(System.in)) {
        System.out.print("Name: ");
        while (sc.hasNextLine()) {
            String name = sc.nextLine();
            System.out.println("Name is \"" + name + "\"");
        }
    }

If you want to know the cause of this issue take a look at this link1 and link2 如果您想知道此问题的原因,请查看此link1link2

This might be a better design to avoid duplicated code. 这可能是避免重复代码的更好设计。 Don't have to restrict the loop end condition to the while statement ;) 不必将循环结束条件限制为while语句;)

    try (Scanner sc = new Scanner(System.in)) {
        while (true) {
            System.out.print("Name: ");
            if (!sc.hasNextLine()) break;
            String name = sc.nextLine();
            System.out.println("Name is \"" + name + "\"");
        }
    }

EDIT : Your edit does not work correctly because sc.nextInt() is not eating the line feed, so put sc.nextLine() after the sc.nextInt() . 编辑 :您的编辑工作不正常,因为sc.nextInt()是不是吃了换行,这样就把sc.nextLine()sc.nextInt()

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM