Tuesday 5 December 2017

Java user input nextLine() doesnt wait for input





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?



itemprop="text">
class="normal">Answer



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

}


}




No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...