2

I have this small problem with my input :

public void input() 
{
    Scanner scn = new Scanner( System.in );
    System.out.print( "Please enter id: " );
    id = scn.nextInt();
    System.out.print( "Please enter name: " );
    title = scn.nextLine();
    System.out.print( "Please enter author: " );
    author = scn.nextLine();
}

Now I'm using scn.nextLine() because I want to have spaces when giving the name and the author like :

USER INPUT:
    Story of Something
    Sir Whatever

The problem is when I use nextLine() the program doesn't wait for my input, it just continues and my console will look like this:

Please enter id: 4632
Please enter name: Please enter author: what, why??

Any way to fix this, please help?

Mosam Mehta
  • 1,590
  • 5
  • 21
  • 32
DisasterCoder
  • 397
  • 1
  • 2
  • 14
  • This is quite a common problem - basically `nextInt()` doesn't consume the newline character immediately after the number, so you need a call to `.nextLine()` immediately after it to get rid of it. – JonK Oct 16 '15 at 08:04

1 Answers1

1

One thing I would do is set up the id as string. I mean to save yourself the headache, unless you are doing something that requires for you to save that as an actual integer then I suggest moving the Id to the very end.

import java.util.Scanner;

public class LetsLearnJava {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String title, author, id;

    Scanner myScan = new Scanner( System.in );

    System.out.print( "Please enter id: " );
    id = myScan.nextLine();

    System.out.print( "Please enter name: " );
    title = myScan.nextLine();

    System.out.print( "Please enter author: " );
    author = myScan.nextLine();

    System.out.print("You entered: " + id + " " +  title + " " + author);

}

}

  • Yea that would be nice to look at I guess but my instructions say that the id has to be int, so I mustn't do it like that.. thanks anyway! – DisasterCoder Oct 16 '15 at 09:33