In this java program, you’ll learn how to get input from the user in Java. We are using the Scanner
class to get input from the user. In the below example, we are getting String input, integer Input, and a float number input. In the below example, we used the nextLine()
, nextInt()
and nextFloat()
method, which is used to read Strings, integer, and float point numbers. To read other types, look at the table below:
Method |
Description |
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 an 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 |
//Java Program to Get Input From User
import java.util.Scanner;
public class JavaPrograms {
public static void main(String[] args) {
int intNum;
float floatNum;
String str;
Scanner input = new Scanner(System.in);
// Get input String
System.out.println("Enter a string: ");
str = input.nextLine();
System.out.println("Input String is: " + str);
// Get input Integer
System.out.println("Enter an integer: ");
intNum = input.nextInt();
System.out.println("Input Integer is: " + intNum);
// Get input float number
System.out.println("Enter a float number: ");
floatNum = input.nextFloat();
System.out.println("Input Float number is: " + floatNum);
}
}
Enter a string:
tutorialsrack
Input String is: tutorialsrack
Enter an integer:
222
Input Integer is: 222
Enter a float number:
2.22
Input Float number is: 2.22
Note: If you enter the wrong input (e.g. text in a numerical input), you will get an exception/error message (like "InputMismatchException").
Comments