1

I have a bit of a problem with a part of my code.

if (option1 == 1){
   //Add Movie
   System.out.print('\u000C');
   System.out.println(">>Add Movie<<");
   System.out.println("");
   System.out.print("Title: ");
   String title = scan.nextLine();
   System.out.print("Year: ");
   int year = scan.nextInt();
}

When i execute the code, it prints out,

Title: Year: 

completely skipping the scan.nextLine(); so I'm unable to put any input for it.

Does anyone have an idea on why it is doing this?

EDIT:

I've managed up to fix this. Turns out if was a scan.nextLine(); error and it had not fully moved to a new line. Thanks everyone :)

Victor Polevoy
  • 12,735
  • 7
  • 68
  • 134
P.L
  • 19
  • 2
  • i doubt that this is your only code. It rather looks like you have another call of `nextInt` or some other `nextFoo` method (excluding `nextLine`) before you do `System.out.print("Title: ");`. You are most likely just catching the carriage return that you didn´t catch beforehand. Assuming i am right you could check [this](http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods) for further information. – SomeJavaGuy Oct 21 '15 at 10:02
  • Kindly show your full code. – Naman Gala Oct 21 '15 at 10:09
  • Please show full code (Also code that scan `option1`). Better if you paste full class after removing unnecessary code. – ashiquzzaman33 Oct 21 '15 at 10:12
  • @Zaman sorry what do you mean by code scan? – P.L Oct 21 '15 at 10:13
  • @Preet, he mean the code which take input for `option1` variable. Kindly share your full code. – Naman Gala Oct 21 '15 at 10:15

3 Answers3

0

Maybe before this code there has a next() family

input.nextInt();
input.next();

input.next....(); //Excluding input.nextLine()

Which doesn't consume extra newline, that consumed by your statement

String title = scan.nextLine();

to resolve this you may add extra nextLine() before those code.

So this code should work

scan.nextLine(); //Consume extra new line
System.out.print("Title: ");
String title = scan.nextLine();
System.out.print("Year: ");
int year = scan.nextInt();
ashiquzzaman33
  • 5,451
  • 5
  • 29
  • 39
0

For me the code is working fine-

Scanner scan=new Scanner(System.in);
    System.out.print("title: ");
    String title=scan.nextLine();

    System.out.print("year: ");
    int year=scan.nextInt();
    System.out.println("title is: "+title+" and year is: "+year);

the output i am getting is this-

title: king
year: 2015
title is: king and year is: 2015
Aritro Sen
  • 347
  • 7
  • 14
-1

tyr this code.

Scanner scan=new Scanner(System.in);
System.out.print("Title: ");
String title = scan.nextLine();
M S Parmar
  • 935
  • 8
  • 21