How to take Java User Input
Now. we learn how can we take input from user in Java. So, we can take input from user in java using Scanner class which is present in java.util package . See below code how to take Java user input.
To use the Scanner class that is present in java.util package, create an object of the class Scanner and use any available methods or functions that are found in the Scanner class . In below example, we will use the nextLine() method, which is used to read Strings(textual message):
import java.util.Scanner; // import the Scanner class form java.util package class Main { public static void main(String[] args) { Scanner Obj = new Scanner(System.in); String userName; // Enter username and press Enter System.out.println("Enter username"); userName = Obj.nextLine(); System.out.println("Username is: " + userName); } }
Output
Enter username usman Username is: usman
Methods to take Java User Input
This is how you could read a string input from user others types of input like numeric, character etc here below are methods which can be used for taking input from user:
Methods | Description |
---|---|
nextInt() | read integer value form user |
nextFloat() | read float(decimal/floating point numbers) value form user |
nextDouble() | read double(decimal/floating point numbers) value form user also but have more range than float |
nextLong() | read long integer/numeric value form user |
nextBoolean() | read boolean value form user |
nextByte() | read byte value form user |
nextLine() | read a string value form user |
nextShort() | read short value form user |
In the below example , we have use different methods to read data or take inputs of various types:
import java.util.Scanner; // import the Scanner class form java.util package class Main { public static void main(String[] args) { Scanner Obj = new Scanner(System.in); System.out.println("Enter name, age and salary:"); // String input String name = Obj.nextLine(); // Numerical input int age = Obj.nextInt(); double salary = Obj.nextDouble(); // Output input by user System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Salary: " + salary); } }
Output
Enter name, age and salary: usman 10 10000 Name: usman Age: 10 Salary: 10000
Link:Â https://Codelikechamp.com
Medium Link: Follow me on Medium
Linkedin Link: Follow me on Linkedin