so I am trying to use the scanner class to receive a few different inputs from a user. They can enter in a movie title, year, director, duration, actors, and genre.
However, for one of the user inputs, it is printing the director and duration together.
Here is a screenshot for more reference. Why is is asking for user input for director and duration at the same time but expecting a user input for duration?
System.out.println("Enter the title: ");
String title = myObj.nextLine();
System.out.println("Enter the year: ");
int year = myObj.nextInt();
System.out.println("Enter the duration: ");
int duration = myObj.nextInt();
System.out.println("Enter the director: ");
String director = myObj.nextLine();
System.out.println("Enter the actors: ");
String actors = myObj.nextLine();
System.out.println("Enter the genre: ");
String genre = myObj.nextLine();
int rating = ran.nextInt(10) 1;
CodePudding user response:
Calling nextInt()
will not consume the newline. It will instead be consumed by the subsequent call to nextLine()
when getting the director. To solve this you can instead call nextLine()
and then Integer.parseInt()
to convert the string to an integer.
CodePudding user response:
.nextInt()
will only read the integer provided in the input. Now the scanner cursor is at "/n"(newline). To avoid this you can either use
int duration = Integer.parseInt(myObj.nextLine());
or
int duration = myObj.nextInt();
myObj.nextLine();