Question
Every line of input will contain a String followed by an integer. Each String will have a maximum of 10 alphabetic characters, and each integer will be in the inclusive range from 0 to 999
Output Code
In each line of output there should be two columns: The first column contains the String and is left justified using exactly 15 characters. The second column contains the integer, expressed in exactly 3 digits; if the original input has less than three digits, you must pad your output's leading digits with zeroes.
Check out this link for more info: hackerrank/challenges/java-output-formatting
This is the code(Java) I wrote:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("================================");
for(int i=0 ; i<3 ; i++){
String s1=sc.next();
int x=sc.nextInt();
System.out.printf("%-15s%03d\n",s1,x);
}
System.out.println("================================");
}
}
My exact doubt/question
While the above code compiled and ran perfectly, I decided to make some changes and try out something different. I added the following line of code just after the line
int x=sc.nextInt();
The line that I added was:
sc.next();
However, after adding that line of code, the program would no longer accept input after the first line. That is only the first line of input would be printed and the next line ignored(not printed). I changed the code sc.next() to sc.nextLine() but now the program would only print the first 2 lines and skip printing the last line(the code I wrote should accept 3 lines of text and print those three lines to standard output using printf). Could anyone please explain why this is happening?
I read online that if I have to read a string after reading integer using next() and nextInt() respectively, then I need to add an extra next() or nextLine() call after reading the integer and before reading the string. (This is to move the scanner to the next character as the escape character was ignored by nextInt()).
In my program, during the first iteration of the loop, the last reading from the standard input happens while reading the integer. At the beginning of the second iteration string is the first to be read. Hence noticing this I made the changes and the program didn't run as planned. However if I remove the extra read in between, the program works perfectly.
Could anyone please explain why this is happening?
Thanks in advance