Code Examples
import java.util.Scanner;
public class BasicScannerInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Hello, " + name + "! You are " + age + " years old.");
scanner.close();
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class BufferedReaderInput {
public static void main(String[] args) {
try (BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in))) {
System.out.print("Enter multiple lines (type 'exit' to stop):\n");
String line;
while (!(line = reader.readLine()).equals("exit")) {
System.out.println("You entered: " + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
graph TD
A[Input Processing] --> B{Input Method}
B --> |Simple Input| C[Scanner]
B --> |Complex Input| D[BufferedReader]
B --> |Parsing Required| E[Scanner with Parsing]
| Method |
Pros |
Cons |
Best For |
| Scanner |
Easy to use |
Less efficient |
Simple inputs |
| BufferedReader |
Efficient |
More complex |
Large text inputs |
| System.in.read() |
Low-level |
Requires manual parsing |
Byte-level reading |
import java.util.Scanner;
public class MultipleInputTypes {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter integer, double, and string:");
int intValue = scanner.nextInt();
double doubleValue = scanner.nextDouble();
String stringValue = scanner.next();
System.out.printf("Inputs: %d, %.2f, %s\n",
intValue, doubleValue, stringValue);
scanner.close();
}
}
Error Handling Techniques
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputErrorHandling {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
System.out.println("You entered: " + number);
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter an integer.");
} finally {
scanner.close();
}
}
}
LabEx Learning Tip
At LabEx, we recommend practicing these input techniques through interactive coding challenges to build robust input handling skills in Java.