Taking input:
Getting Started: We must import the java.util.Scanner package in order to use the Scanner class.
import java.util.Scanner;
Recently, the Scanner class was imported. To use the Scanner class’s methods, we construct an object of that class.
Scanner sc = new Scanner(System.in)
The System.in is passed as a parameter and is used to take input.
Note: Your object can be named anything, there is no specific convention to follow. But we normally name our object sc for easy use and implementation.
An object of the scanner class can be created in four different ways. Let’s look at how to generate scanner objects.
- Reading keyboard input:
Scanner sc = new Scanner(System.in)
- Reading String input:
Scanner sc = new Scanner(String str)
- Reading input stream:
import java.util.Scanner;
- Reading File input:
Scanner sc = new Scanner(File file)
How does a Scanner class operate then?
The inputs are read by the scanner object, which then tokenizes the string. Whitespaces and newlines are the usual criteria used to split the tokens.
Example:
Susan
19
78.95
O
The input above will be separated into the letters “Susan,” “19,” “78.95,” and “O.” Depending on the type of Scanner object produced, the Scanner object will then iterate over each token and read it.
Now that we’ve seen how the Scanner object is made, we can see the various ways it may be made, how it reads input, and how it functions. Let’s examine various approaches to gathering input.
The scanner class’s methods are listed below:
Method | Description |
nextLine() | Accepts string value |
next() | Accept string till whitespace |
nextInt() | Accepts int value |
nextFloat() | Accepts float value |
nextDouble() | Accepts double value |
nextLong() | Accepts long value |
nextShort() | Accepts short value |
nextBoolean() | Accepts Boolean value |
nextByte() | Accepts Byte value |
Example:
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Name, RollNo, Marks, Grade");
String name = sc.nextLine(); //used to read line
int RollNo = sc.nextInt(); //used to read int
double Marks = sc.nextDouble(); //used to read double
char Grade = sc.next().charAt(0); //used to read till space
System.out.println("Name: "+name);
System.out.println("Gender: "+RollNo);
System.out.println("Marks: "+Marks);
System.out.println("Grade: "+Grade);
sc.close();
}
}
Output:
Enter Name, RollNo, Marks, Grade
Mohit
19
87.25
A
Name: Mohit
Gender: 19
Marks: 87.25
Grade: A