首页 > 解决方案 > 在 Java 中使用 Scanner 函数的意外行为

问题描述

所以我试图让用户输入一条消息和一个整数。整数决定了消息将被打印到屏幕上的次数。我正在使用 for 循环进行重复。

我现在的问题是,当我让用户先输入消息然后输入整数时,一切正常,但是当我反过来做时,它不允许我在输入整数后输入消息。输入整数并按回车后,它会显示输入消息的提示,然后立即退出程序。

是什么导致了这种行为?

// This application lets the user enter an integer and a message.
// The message is printed as many times as the integer that was specified.

package en.hkr;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int x;
    String message;

    // Does not work the other way around?
    System.out.print("Enter a message: ");
    message = input.nextLine();
    System.out.print("Enter an integer: ");
    x = input.nextInt();



    // for loop
    for(int i = 0; i < x; i++) {
        System.out.println(message);
    }
}
}

标签: javainputjava.util.scanner

解决方案


相关答案。

打电话nextLinenextInt打电话。你需要这个来消耗线路的其余部分。

System.out.print("Enter an integer: ");
x = input.nextInt();
input.nextLine(); // Add this right here
System.out.print("Enter a message: ");
message = input.nextLine();

或者,您可以只使用nextLine代替nextInt并单独解析它。由于Scanner' 有时令人困惑的性质,这将是我的方法。


推荐阅读