My code is as follows:
import java.util.Scanner;
public class GetUserInput {
public static void main (String args[]) {
int i;
float f ;
String s;
Scanner input = new Scanner (System.in);
System.out.println ("enter an integer: ");
i = input.nextInt();
System.out.println ("you entered an integer equal to " + i);
System.out.println ("enter a floating point number: ");
f = input.nextFloat();
System.out.println ("You entered a floating point number equal to " + f );
System.out.println ("enter a sentence: ");
s = input.nextLine();
System.out.println ("You entered a sentence which is \" " +s+ " \" ");
}
}
Output:
D:\Java Codebase>javac GetUserInput.java
D:\Java Codebase>java GetUserInput
enter an integer:
2
you entered an integer equal to 2
enter a floating point number:
7
You entered a floating point number equal to 7.0
enter a sentence:
You entered a sentence which is " "
My Query is: input.nextLine() does not wait for user input. Instead it continues execution from next line. But if I move up input.nextLine(); before both input.nextInt(); and input.nextFloat() in the above code, the execution works fine, input.nextLine(); waits for user input. edited code and output are as follows.
import java.util.Scanner;
public class GetUserInput {
public static void main (String args[]) {
int i;
float f ;
String s;
Scanner input = new Scanner (System.in);
System.out.println ("enter a sentence: ");
s = input.nextLine();
System.out.println ("You entered a sentence which is \" " +s+ " \" ");
System.out.println ("enter an integer: ");
i = input.nextInt();
System.out.println ("you entered an integer equal to " + i);
System.out.println ("enter a floating point number: ");
f = input.nextFloat();
System.out.println ("You entered a floating point number equal to " + f );
}
}
output:
D:\Java Codebase>javac GetUserInput.java
D:\Java Codebase>java GetUserInput
enter a sentence:
hi
You entered a sentence which is " hi "
enter an integer:
1
you entered an integer equal to 1
enter a floating point number:
8
You entered a floating point number equal to 8.0
Clarifications Invited.
Thanks in advance,
Satya