How to get user input in Java
By:Roy.LiuLast updated:2019-08-11
In Java, we can use java.util.Scanner to get user input from console.
1. Scanner
1.1 Read a line.
UserInputExample1.java
package com.mkyong; import java.util.Scanner; public class UserInputExample1 { public static void main(String[] args) { // auto close scanner try (Scanner scanner = new Scanner(System.in)) { System.out.print("Enter something : "); String input = scanner.nextLine(); // Read user input System.out.println("User Input : " + input);
Output
Enter something : hello world User Input : hello world
1.1 Read different data type
UserInputExample2.java
package com.mkyong; import java.util.Scanner; public class UserInputExample2 { public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in)) { System.out.println("Please enter your name : "); String name = scanner.next(); // get string System.out.println("Please enter your age : "); int age = scanner.nextInt(); // get integer System.out.println("Please enter your salary : "); double salary = scanner.nextDouble(); // get double System.out.format("Name : %s, Age : %d, Salary : %.2f", name, age, salary);
Output
Please enter your name : mkyong Please enter your age : 38 Please enter your salary : 9000 Name : mkyong, Age : 38, Salary : 9000.00
2. InputStreamReader + BufferedReader
2.1 Alternative solution.
package com.mkyong; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class UserInputExample { public static void main(String[] args) throws IOException { try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { System.out.println("Please enter your name : "); String name = br.readLine(); System.out.println("Please enter your age : "); int age = Integer.parseInt(br.readLine()); System.out.println("Please enter your salary : "); double salary = Double.parseDouble(br.readLine()); System.out.format("Name : %s, Age : %d, Salary : %.2f", name, age, salary);
Output
Please enter your name : Steve Jobs Please enter your age : 56 Please enter your salary : 1.00 Name : Steve Jobs, Age : 56, Salary : 1.00
From:一号门
COMMENTS