-2

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?

Code and Output

    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;
Aman
  • 11
  • 3

2 Answers2

1

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.

YGL
  • 5,540
  • 2
  • 22
  • 19
  • Oh ok, so what I think you are saying is that the nextInt() does not take the entire new line. Therefore, the remaining blank space, for the nextLine() is consumed by the following call. That is terrible wording on my behalf. – Aman Sep 23 '21 at 05:19
0

.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();

Akash_ATG
  • 7
  • 2