0

I want to read an int, double and string and add each one to a variable but I can't read the string.

int i = 4;
double d = 4.0;
String s = "My name is ";   
Scanner scan = new Scanner(System.in);
int i2 = scan.nextInt();
double d2 = scan.nextDouble();
String s2 = scan.nextLine();        
System.out.println(i+i2);
System.out.println(d+d2);
System.out.println(s + s2);
scan.close();

my understanding is that scan.nextLine() reads a string but it just skips it. scan.next() just reads the first word. it works properly if i added scan.nextLine(); before String str2 = scan.nextLine(); but i dont know why

Steven
  • 23
  • 1
  • 7

1 Answers1

-1

for the input

 2.4
 "Some String"

When you use nextDouble only 2.4 is picked not the EndOfLine (after 2.4 and before "Some String".). Hence your code worked by using 2 nextLine().

You could also use

int i2 = Integer.parseInt(scan.nextLine());
double d2 = Double.parseDouble(scan.nextLine());
String str2 = scan.nextLine();  
Loki
  • 738
  • 3
  • 12