0

I am working on a project that requires me to prompt the user for how many lines they would like to enter. Then for each line it will prompt for a string of numbers, separated by spaces, and put it into an array once entered. Here is the code I am using:

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));       
}

when I try to run this, the first line will immediately skip the first line without allowing any user input. any following lines will work fine. the output is as follows:

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]

I've tried to use next() instead of nextLine() which resolves this issue, but when I do that the entry.split() command creates an array out of only the first number in the entry. this is an example of what happens when I use next():

Enter the string of numbers:
5 4 3 2 1
numbers = [5]

any advice would be greatly appreciated!

gravyGus
  • 11
  • 2
  • You probably used any of the `nextXXX` before `nextLine`. We cant tell because you did not share your full code... – Zabuzard Aug 27 '21 at 18:06

0 Answers0