java - 在 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);
}
}
}
解决方案
打电话nextLine
后nextInt
打电话。你需要这个来消耗线路的其余部分。
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
' 有时令人困惑的性质,这将是我的方法。
推荐阅读
- python - keras:您必须使用 dtype float 和 shape [?,224,224,3] 为占位符张量“input_1”提供一个值
- python - 多个进程的Python3管道输出到单个进程
- jquery - Ajax POST 调用返回 404,即使脚本存在
- c# - 在 Visual Studio 中调试时,某些对象显示为 System.__ComObject
- java - 为什么每次单击时它都会移动同一个圆圈,而不管距离如何?
- c - 使用 c 从字符串中删除重复的连续字符
- go - 我应该使用哪种协议在多个节点之间交换文件?
- java - Lamba 表达式会自动为其入口参数创建新对象吗?
- php - 如何在 Laravel 5.6 中使用路由模型绑定更新用户
- python - 如何将 Pandas DataFrame Column 值与多级索引进行比较?