-1

Consider the following snippet:

    System.out.print("input iteration cycles");
    Scanner reader=new Scanner(System.in);
    int iteration = reader.nextInt();
    System.out.print("input choice: Var or par");
    String choice=reader.nextLine();
    System.out.print(choice);

I was hoping to get one line where it prints the first input and the next print out to only print the next input which is either var or par, however it seems that the second print prints out the second input in addition to the first input. Any idea why?

Sandeep Chatterjee
  • 3,110
  • 7
  • 25
  • 44
B.rabbit
  • 69
  • 1
  • 11
  • I would also recomment you this [post](http://christprogramming.wordpress.com/2014/01/30/java-common-mistakes-1/) for further information. – Christian Mar 21 '14 at 18:36
  • I actually googled and saw the page just now so I added reader.nextLine(); before String choice=reader.nextLine(); but the output was still the same as before – B.rabbit Mar 21 '14 at 18:39
  • Actually its a stupid mistake on my part. I missed out the fact that I printed the values at the end of the code without leaving a newline making me think that it concatenated the answers. but thanks guys, guess I'll accept your answers even though it was a totally diff error on my part >_ – B.rabbit Mar 21 '14 at 19:11

1 Answers1

2

nextInt() does not advance to the next line. So you must make an explicit call to nextLine() immediately after it. Otherwise, choice will be given that newline. Just add this line to your code:

System.out.print("input iteration cycles");
Scanner reader=new Scanner(System.in);
int iteration = reader.nextInt();
reader.nextLine(); //<==ADD
System.out.print("input choice: Var or par");
String choice=reader.nextLine();
System.out.print(choice);
Edwin Torres
  • 2,491
  • 1
  • 11
  • 15