Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanner class is skipping lines

Tags:

java

I'm new to programing and I'm having a problem with my scanner class. This code is in a loop and when the loop comes around the second, third whatever time I have it set to it skips the first title input. I need help please why is it skipping my title scanner input in the beginning?

System.out.println("Title:");

list[i].title=keyboard.nextLine();

System.out.println("Author:");

list[i].author=keyboard.nextLine();

System.out.println("Album:");

list[i].album=keyboard.nextLine();

System.out.println("Filename:");

list[i].filename=keyboard.nextLine();
like image 491
Ivan_Stepul Avatar asked Dec 06 '25 06:12

Ivan_Stepul


1 Answers

It is likely that, in the code you haven't shown us, there exists a call to one of Scanner input methods that does not consume a newline method. nextLine for example. In this instance the newline character will be passed from the end of the loop to the subsequent nextLine statement. This now will not block having received input. The solution is to ensure the newline is consumed at the end of each iteration

// list[i].id = keyboard.nextInt();
list[i].id = Integer.parseInt(keyboard.nextLine());
like image 171
Reimeus Avatar answered Dec 08 '25 19:12

Reimeus