Java Tutorials
Java Methods
Java Classes
Java File Handling
The scanner
class is used to find user input, and is available in the java.util
package.
To use the scanner
class, create a class object and use any of the methods available in the scanner
class. In our example, we will use the following nextLine()
method, which is used to read Cables:
import java.util.Scanner; // Import the Scanner class
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
}
}
In the example above, we used the following method nextLine()
, which is used to read Strings. To learn more about the genres, see 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 a 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 |
In the example below, we use a variety of methods to read data of different types:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter name, age and salary:");
// String input
String name = myObj.nextLine();
// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();
// Output input by user
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
Note: If you enter incorrect input (eg text in numerical input), you will get an error / error message (such as "InputMismatchException").