1
Scanner s = new Scanner(System.in)  
int x = S.nextInt();  
double y = S.nextDouble();  
S.nextLine();  //Why 
String z = S.nextLine();  

Why do I need to type S.nextLine() after reading int & double before I can read a String ?

Ahmed Usama
  • 113
  • 8
  • 2
    [This post](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) might help you. – QBrute Aug 09 '18 at 19:14
  • 1
    If i remove it , the program will ignore reading the String @KarolDowbecki – Ahmed Usama Aug 09 '18 at 19:15

1 Answers1

3

If you have the following information

Line 1: 1.0 2.0 4.0(you are currently here after reading the double 4.0) \n
Line 2: (you are here once you eat that '\n' character using readLine())

Once you store the last digit: 4, you are still on that same line (line 1). You need to eat up that new line character. s.nextLine() will read until the end of the line and return an empty result. Once that is done the scanner is positioned at the beginning of Line 2.

Dr3amer17
  • 41
  • 6