In Java, you can use the Scanner class and the Console class to interact with the user via the command line for input and output. Here are examples of how to use both classes for input:
Scanner class
In Java, the Scanner class from the java.util package is employed for acquiring input of primitive types such as int, double, as well as strings.
While using the Scanner class is the simplest method for reading input in a Java program, it may not be the most efficient choice for situations where input processing time is critical, such as competitive programming.
Syntax:-
Scanner sc=new Scanner(System.in);
Methods of Java Scanner Class
nextBoolean(): Used for reading a Boolean value.
nextByte(): Used for reading a Byte value.
nextDouble(): Used for reading a Double value.
nextFloat(): Used for reading a Float value.
nextInt(): Used for reading an Int value.
nextLine(): Used for reading a Line value (usually a String).
nextLong(): Used for reading a Long value.
nextShort(): Used for reading a Short value.
"Let's examine a code snippet that demonstrates how to read input of various data types."
Example:-
// Java program to read data of various types using Scanner
// class.
import java.util.Scanner;
public class ScannerDemo1 {
public static void main(String[] args)
{
// Declare the object and initialize with
// predefined standard input object
Scanner sc = new Scanner(System.in);
// String input
String name = sc.nextLine();
// Character input
char gender = sc.next().charAt(0);
// Numerical data input
// byte, short and float can be read
// using similar-named functions.
int age = sc.nextInt();
double cgpa = sc.nextDouble();
// Print the values to check if the input was
// correctly obtained.
System.out.println("Name: " + name);
System.out.println("Gender: " + gender);
System.out.println("Age: " + age);
System.out.println("CGPA: " + cgpa);
}
}
1.It imports the Scanner class to facilitate user input.
2.In the main method:
It creates a Scanner object sc to read input from the standard input stream (System.in).
It uses sc.nextLine() to read a line of input as a String and stores it in the name variable.
It uses sc.next().charAt(0) to read the next token (word) as a String and then extracts the first character of that string as a char, storing it in the gender variable.
It uses sc.nextInt() to read the next token as an int and stores it in the age variable.
It uses sc.nextDouble() to read the next token as a double and stores it in the cgpa variable.
3.After reading all the values, it prints them to the console to verify that the input was correctly obtained.
Input
Abhay Mishra
Male
24
91
Output
Name: Abhay Mishra
Gender: M
Age: 24
CGPA: 91.0
Sometimes, it's necessary to verify if the next value we're about to read is of a specific data type or if the input has reached its end (EOF marker encountered).
To accomplish this, we can utilize the hasNextXYZ() functions, where XYZ represents the type we are interested in. These functions return true if the Scanner has a token of the specified type, and false otherwise. For example, in the code below, we have employed hasNextInt() to check for an integer input. To check for a string, we use hasNextLine(), and for a single character, we use hasNext().charAt(0)
Let's review a code snippet for reading numbers from the console and calculating their mean
// Java program to read some values using Scanner
// class and print their mean.
import java.util.Scanner;
public class ScannerDemo2 {
public static void main(String[] args)
{
// Declare an object and initialize with
// predefined standard input object
Scanner sc = new Scanner(System.in);
// Initialize sum and count of input elements
int sum = 0, count = 0;
// Check if an int value is available
while (sc.hasNextInt()) {
// Read an int value
int num = sc.nextInt();
sum += num;
count++;
}
if (count > 0) {
int mean = sum / count;
System.out.println("Mean: " + mean);
}
else {
System.out.println(
"No integers were input. Mean cannot be calculated.");
}
}
}
This Java program reads integer values from the standard input using the Scanner class and calculates their mean (average). Here's a breakdown of how the program works:
1.It imports the Scanner class to facilitate user input.
2.In the main method:
It creates a Scanner object sc to read input from the standard input stream (System.in).
Initializes two variables, sum and count, to keep track of the sum of input values and the count of input values, respectively.
Uses a while loop to continuously check if the next input is an integer using sc.hasNextInt(). If an integer is available, it reads the integer value using sc.nextInt(), adds it to the sum, and increments the count.
3.After the loop, it checks whether any integers were input (i.e., count > 0). If count is greater than zero, it calculates the mean (average) by dividing sum by count and then prints the mean value. If no integers were input (i.e., count is still zero), it prints a message stating that the mean cannot be calculated.
Input:
1
2
3
4
5
Output:
Mean: 3
Importing the Class: To use the Scanner class, you need to import it with import java.util.Scanner;.
Reading from Standard Input: The Scanner class is commonly used to read input from the standard input stream (System.in) by creating a Scanner object with System.in as the argument.
Reading from Files: You can also read input from files by passing a File object as an argument to the Scanner constructor.
Reading Different Data Types: Scanner provides methods like nextByte(), nextInt(), nextLong(), nextFloat(), nextDouble(), etc., to read different data types.
Reading Strings: To read strings, you can use next() or nextLine() methods. next() reads the next token (usually a word), while nextLine() reads the entire line.
Reading Characters: You can read a single character by combining next() and charAt(0), as in next().charAt(0).
Delimiter: By default, Scanner uses whitespace as the delimiter to separate tokens. You can change the delimiter using the useDelimiter() method.
Checking for Input: You can check if there is more input to read with methods like hasNext(), hasNextInt(), hasNextLine(), etc.
Closing the Scanner: It's important to close the Scanner object using close() when you're done with it to release resources.
Handling Input Errors: Always validate input using methods like hasNextInt() or exception handling to prevent unexpected program behavior due to invalid input.
Tokenization: Scanner reads input and tokenizes it. Tokens are smaller units of input separated by the specified delimiter.
Locale and Locale-Sensitive Parsing: You can set the locale to influence how Scanner parses numbers and strings. For example, comma (,) or period (.) as a decimal separator.
Not Suitable for Competitive Programming: While Scanner is convenient, it may not be the most efficient choice for scenarios where input processing time is critical, such as competitive programming.
Exception Handling: Be prepared to handle exceptions like InputMismatchException or NoSuchElementException that may occur if the input doesn't match the expected format.
Thread Safety: Scanner is not thread-safe, so avoid sharing Scanner objects between multiple threads without proper synchronization.
Unicode Support: Scanner supports Unicode characters, allowing you to read and process text in various languages.