[post-views]

In this lesson, you will learn,
Scanner class in Java is part of the java.util package.
You will create an instance of the Scanner class first as follows
//Creates a Scanner object that reads
//from standard input (keyboard).
Scanner scanner = new Scanner(System.in);
Now, the object scanner can be used to read inputs from the keyboard.
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
//Create a Scanner object to read from console
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your full name: ");
// Reads a whole line of text
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
System.out.print("Enter your age: ");
// Reads an integer value
int age = scanner.nextInt();
System.out.println("You are " + age + " years old.");
//Close the scanner when it's no longer needed
scanner.close();
}
}
Output
Enter your full name: Amit Kumar
Hello, Amit Kumar!
Enter your age: 29
You are 29 years old.
Explanation
In this example, a Scanner object is created to read data from the standard input (keyboard).
The nextLine() method reads a string (until the user presses Enter), and the nextInt() method reads an integer.
Important Note!
Similar to nextInt() method, the nextFloat(), nextDouble(), and nextLong() methods can be used to take float, double, and long values.
Below is a table summarizing some of the common methods of the Scanner class in Java, their purposes, and example usages:
| Method | Description | Example Usage |
|---|---|---|
next() |
Finds and returns the next complete token from this scanner. | String s = scanner.next(); |
nextLine() |
Advances this scanner past the current line and returns the input that was skipped. | String line = scanner.nextLine(); |
nextInt() |
Scans the next token of the input as an int. |
int i = scanner.nextInt(); |
nextDouble() |
Scans the next token of the input as a double. |
double d = scanner.nextDouble(); |
nextFloat() |
Scans the next token of the input as a float. |
float f = scanner.nextFloat(); |
nextLong() |
Scans the next token of the input as a long. |
long l = scanner.nextLong(); |
hasNext() |
Returns true if this scanner has another token in its input. |
boolean b = scanner.hasNext(); |
hasNextInt() |
Returns true if the next token in this scanner’s input can be interpreted as an int. |
boolean b = scanner.hasNextInt(); |
hasNextDouble() |
Returns true if the next token in this scanner’s input can be interpreted as a double. |
boolean b = scanner.hasNextDouble(); |
useDelimiter(String pattern) |
Sets this scanner’s delimiting pattern to the specified pattern. | scanner.useDelimiter(","); |
close() |
Closes this scanner. | scanner.close(); |
next() method of the Scanner class in Java is used to find and return the next complete token from the input source.
next() Method
import java.util.Scanner;
public class NextMethodExample {
public static void main(String[] args) {
// Create a Scanner object
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a line of text:");
String firstWord = scanner.next(); // Reads the first word
String secondWord = scanner.next(); // Reads the second word
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
// It's always a good practice to close the scanner
scanner.close();
}
}
Output
Enter a line of text:
Hello World from Java
First word: Hello
Second word: World
Explanation
The next() method only reads up to the first occurrence of whitespace, effectively parsing the input into individual tokens that can be processed separately.
Note that in this example, if you enter more than two words, only the first two will be processed because we only called next() twice.
Additional calls to next() would continue to return subsequent tokens from the input.
Using Different Delimiters: The Scanner can use custom delimiters instead of whitespace.
Scanner scanner = new Scanner("apple, banana, cherry");
scanner.useDelimiter(", ");
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
scanner.close();
In this case, the scanner is using a comma followed by a space as the delimiter to tokenize the input string.
hasNextInt() MethodThe hasNextInt() method of the Scanner class in Java is used to check if the next token in the scanner’s input can be interpreted as an int value in the default radix.
package ch3;
import java.util.Scanner;
public class HasNextIntExample {
public static void main(String[] args) {
// Create a Scanner object
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a list of integer values. "
+ "Enter any non-integer to stop:");
// Continuously read intesgers from the console
while (scanner.hasNextInt()) {
int value = scanner.nextInt();
System.out.println("You entered the integer: " + value);
}
System.out.println("Non-integer input detected. Exiting...");
// Close the scanner
scanner.close();
}
}
Output
Enter a list of integer values. Enter any non-integer to stop:
10 20 30 34.5
You entered the integer: 10
You entered the integer: 20
You entered the integer: 30
Non-integer input detected. Exiting...
Note: It allows you to ensure that the next input can be safely read as an integer before attempting to read it, thereby avoiding InputMismatchException.
1. Parsing of Primitive Types and Strings:
Scanner class can read and parse various data types including int, long, double, float, byte, short, boolean, and String.nextInt(), nextDouble(), nextBoolean(), nextLine(), etc.2. Tokenization
useDelimiter(String pattern) method.3. Flexible Source of Input
InputStream (like System.in), File, Path, or String.
import java.util.Scanner;
public class EvenOddChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
if (num % 2 == 0) {
System.out.println(num + " is even.");
} else {
System.out.println(num + " is odd.");
}
scanner.close();
}
}
import java.util.Scanner;
public class InterestCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter principal amount: ");
double principal = scanner.nextDouble();
System.out.print("Enter rate of interest (in %): ");
double rate = scanner.nextDouble();
System.out.print("Enter time (in years): ");
double time = scanner.nextDouble();
double interest = (principal * rate * time) / 100;
System.out.println("Simple Interest: " + interest);
scanner.close();
}
}
good
You must be logged in to submit a review.