Stdin and Stdout in Java

From the title it looks very obvious that java standard input and out is quite a small and basic thing to know. However while solving some basic programs on HackerRank website, I discovered few things which I did not know or ever used. Still good to know it.

Task:
1- Accept an integer from console
2- Accept a string from console
Print
Integer: <input integer>
String: <InputString>

This looks very basic as one would simply write as below:
Scanner sc =new Scanner(System.in);
int i= sc.nextInt();
String s=sc.next();

However the output would be as below:
Console Input:
4
Hello, How are you?

Output:
4

It wont print the string because:
Step1- Enter number in console ( The number is stored in int i)
Step2: User hits Enter key ( next() will read the string till space, i.e Hello,

To implement it we need to use nextLine()
So updated code will be:
int i= sc.nextInt();
String s=sc.nextLine();

But here also there is an issue, since nextLine() will Enter as an input which is empty in this case. So it will not print the string at all.

So we need to skip enter key input as below:
int i=sc.nextInt();
sc.nextLine(); //This will take the Enter key as input
String s=sc.nextLine(); This will print the entire sentence
sc.close();

Leave a Reply