Reputation: 173
It is a simple java code.. but Scanner class isn't taking the string as input. why?
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int x=sc.nextInt();
double y=sc.nextDouble();
String s =sc.nextLine();
System.out.println("String: "+s);
System.out.println("Double: "+y);
System.out.println("Int: "+x);
}
Upvotes: 2
Views: 379
Reputation: 2254
Because the sc.nextInt()
and sc.nextDouble()
method does not consume the newline character of your input, so that newline is consumed in the next call to sc.nextLine()
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int x=sc.nextInt();
sc.nextLine();
double y=sc.nextDouble();
sc.nextLine();
String s =sc.nextLine();
System.out.println("String: "+s);
System.out.println("Double: "+y);
System.out.println("Int: "+x);
}
Upvotes: 2
Reputation: 1069
Use nextLine()
method to read all values and then parse them into the corresponding type (Integer, Double, etc). See why here: Integer.parseInt(scanner.nextLine()) vs scanner.nextInt()
Upvotes: 1