Basic Input
Domains:
Java
Java Input
There are several ways to get input from the user in Java. You will learn to get input by using Scanner
object in this article.
For that, you need to import Scanner
class using:
import java.util.Scanner;
Learn more about Java import
Then, we will create an object of Scanner
class which will be used to get input from the user.
Scanner input = new Scanner(System.in); int number = input.nextInt();
Example: Get Integer Input From the User
import java.util.Scanner;
class Input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("You entered " + number);
}
}
When you run the program, the output will be:
Enter an integer: 23 You entered 23
Here, input
object of Scanner
class is created. Then, the nextInt()
method of the Scanner
class is used to get integer input from the user.
To get long
, float
, double
and String
input from the user, you can use nextLong()
, nextFloat()
, nextDouble()
and next()
methods respectively.
Example: Get float, double and String Input
import java.util.Scanner;
class Input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Getting float input
System.out.print("Enter float: ");
float myFloat = input.nextFloat();
System.out.println("Float entered = " + myFloat);
// Getting double input
System.out.print("Enter double: ");
double myDouble = input.nextDouble();
System.out.println("Double entered = " + myDouble);
// Getting String input
System.out.print("Enter text: ");
String myString = input.next();
System.out.println("Text entered = " + myString);
}
}
When you run the program, the output will be:
Enter float: 2.343 Float entered = 2.343 Enter double: -23.4 Double entered = -23.4 Enter text: Hey! Text entered = Hey!