java - 为什么 nextLine() 跳过第一个输入但没有其他输入?
问题描述
我正在做一个项目,该项目需要我提示用户他们想输入多少行。然后对于每一行,它将提示输入一串数字,以空格分隔,并在输入后将其放入数组中。这是我正在使用的代码:
for(int i = 0; i < NumOfLines; i++) {
System.out.print("Enter the string of numbers:");
String entry = sc.nextLine();
String[] line = entry.split(" ");
System.out.println("numbers = " + Arrays.toString(line));
}
当我尝试运行它时,第一行将立即跳过第一行,而不允许任何用户输入。以下任何行都可以正常工作。输出如下:
Enter the number of lines: 3
Enter the string of numbers:numbers = []
Enter the string of numbers:5 4 3 2 1
numbers = [5, 4, 3, 2, 1]
Enter the string of numbers:1 2 3 4 5
numbers = [1, 2, 3, 4, 5]
我尝试使用 next() 而不是 nextLine() 来解决此问题,但是当我这样做时,entry.split() 命令仅使用条目中的第一个数字创建一个数组。这是我使用 next() 时发生的情况的一个示例:
Enter the string of numbers:
5 4 3 2 1
numbers = [5]
任何建议将不胜感激!
解决方案
推荐阅读
- python - 插入新值时出现流入数据库问题
- sql - 在连续 CSV 导入和删除表时清理 SQL 数据库
- powershell - 使用 PS 脚本导出和导入包含 CSV 文件的文件夹结构和绑定
- vba - 将单元格中的前 2 个字符更改为整数(使用循环(VBA))
- ansible - ansible 在加载 YAML 时出现语法错误。没有找到预期的密钥
- visual-studio - 带 * 的 AssemblyVersion 只生成“0.0”
- angular - 如何为 @Inject(DOCUMENT) 文档创建单元测试:Angular 中的文档
- java - 如何使用 @PathVariable 参数映射 ResponseEntity<> getByName 方法?
- javascript - 为什么这个 for 循环不起作用并且我的变量为零?
- javascript - 客户端与服务器端的视频编码