User Input in Java
User Input
Instead of writing hard-coded values. If you want to take input from the user, you can use the Scanner class and easily take input from the user.
Steps For User Input In Java
- First
import java.util.Scanner;. - Create object of Scanner
Scanner sc = new Scanner(System.in);. - Take input from user.
Integer User Input
If you want to take integer input from the user, you can use nextInt() method of Scanner class.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Number: ");
int num = sc.nextInt();
System.out.println("The number you typed is "+num);
}
}
String User Input
If you want to take string input from the user, you can use nextLine() method of Scanner class.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Name: ");
String name = sc.nextLine();
System.out.println("The name you typed is "+name);
}
}
Floating Point User Input
If you want to take floating point input from the user, you can use nextFloat() method of Scanner class.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Number: ");
double number = sc.nextDouble();
System.out.println("The number you typed is "+number);
}
}
Example
Taking first name and last name from user and to print full name.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first name: ");
String firstName = sc.nextLine();
System.out.println("Enter last name: ");
String lastName = sc.nextLine();
String fullName = firstName + " "+ lastName;
System.out.println("Your fullname is "+fullName);
}
}
| Methods | Description |
|---|---|
| sc.nextInt() | For integer user input. |
| sc.nextFloat() | For float user input. |
| sc.nextDouble() | For double user input. |
| sc.nextLine() | For text/ String user input. |
| sc.nextBoolean() | For boolean user input. |