首页 > 解决方案 > 为什么 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]

任何建议将不胜感激!

标签: javaarrays

解决方案


推荐阅读