0

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

Name:但在要求输入之前它不会输出。

控制台只显示一个空的控制台窗口,我可以在其中输入名称。

Name:在询问名称之前如何确保已输出?

编辑

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: ");
    }
4

3 回答 3

0

这可能是避免重复代码的更好设计。不必将循环结束条件限制为 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 + "\"");
        }
    }

编辑:您的编辑无法正常工作,因为sc.nextInt()没有吃掉换行符,所以sc.nextLine()放在sc.nextInt().

于 2016-02-04T02:42:51.623 回答
0

将您的 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: ");
    }
}

扫描仪在运行下一个代码之前一直等到它接收到输入,所以只需将打印放在扫描仪之前,然后放在 while 循环的末尾。

于 2016-02-04T02:34:12.383 回答
0

您应该System.out.print("Name: ");像这样在 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 + "\"");
        }
    }

如果您想知道此问题的原因,请查看此链接1和链接 2

于 2016-02-04T02:34:44.600 回答