The Scanner class is used to get user input, and it is found in the java.util
package.
import java.util.Scanner;
public class UserInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your country: ");
String country = scanner.nextLine();
System.out.println("your country is "+ country);
scanner.close();
}
}
Enter your country:
seoul
your country is seoul
nextLine()
method, which is used to read Strings.
import java.util.Scanner;
public class UserInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number x * 5 = ? ");
boolean hasNextDouble = scanner.hasNextDouble();
if (hasNextDouble){
Double number = scanner.nextDouble();
System.out.println(number * 5);
}
else{
System.out.println("Please enter number");
}
scanner.close();
}
}
Enter number x * 5 = ?
4
20.0
- with hasNextDouble() check user input is number(double type) or not.
nextDouble()
method, which is used to read Double Data type.
Input types
nextBoolean() | Reads a boolean value from the user |
nextByte() | Reads a byte value from the user |
nextDouble() | Reads a double value from the user |
nextFloat() | Reads a float value from the user |
nextInt() | Reads a int value from the user |
nextLine() | Reads a String value from the user |
nextLong() | Reads a long value from the user |
nextShort() | Reads a short value from the user |