0

I ran into a problem that I don't understand. nextLine() should be for sentences, right?

System.out.println("Enter film's name");
a = scan.nextLine();
System.out.println("What number did the film released?");
b = scan.nextInt();
System.out.println("Who's the director?");
c = scan.nextLine();
System.out.println("How long is the film in minutes?");
d = scan.nextInt();
System.out.println("Have you seen the movie? Yes/No?");
e = scan.next();
System.out.println("Mark for the film?");
f = scan.nextDouble();

It runs correctly till the releasing date, and then it shows "Who is the director" and "How long is the film" together and doesn't work like it supposed to work.

How can you use nextLine(); and why doesn't it work for me?

Shahar Hamuzim Rajuan
  • 3,908
  • 4
  • 39
  • 70
KNO3
  • 23
  • 4

2 Answers2

1

The buffer is stuffed really reset your scanner after every consecutive calls. scan.reset(); . The reason is that previous characters are cached in the input stream.

Remario
  • 3,455
  • 2
  • 14
  • 22
  • Also nextInt() does not consume the last newline ascii character in your input. To remdey this, use scan.nextLine() to get int value then Integer.parseInt(scan.nextLine()). However get the integer first , and check if it is a integer then perform the parseInt conversion.Don't use nextInt() or next. – Remario Feb 27 '17 at 13:14
0

Your problem is that Scanner.nextInt() does not reads to the next line. So you need to issue nextLine() calls too and throw away their content:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter film's name");
    String a = scan.nextLine();
    System.out.println("What number did the film released?");
    int b = scan.nextInt();
    scan.nextLine(); // this
    System.out.println("Who's the director?");
    String c = scan.nextLine();
    System.out.println("How long is the film in minutes?");
    int d = scan.nextInt();
    scan.nextLine(); // this
    System.out.println("Have you seen the movie? Yes/No?");
    String e = scan.next();
    System.out.println("Mark for the film?");
    double f = scan.nextDouble();
    scan.nextLine(); // after nextDouble() too
}
Tamas Rev
  • 6,418
  • 4
  • 28
  • 47