Absolutely! Scanner
is easy, BufferedReader
is fast, but what if you need security? If you’re working on a command-line calculator and require secure input handling, Console
is a great option.
System.console()
helps in reading Java user input securely, especially for password-like inputs.
Here’s how you can use it in a calculator:
import java.io.Console;
public class Calculator {
public static void main(String[] args) {
Console console = System.console();
if (console == null) {
System.out.println("No console available!");
return;
}
double num1 = Double.parseDouble(console.readLine("Enter first number: "));
char operator = console.readLine("Enter operator (+, -, *, /): ").charAt(0);
double num2 = Double.parseDouble(console.readLine("Enter second number: "));
double result = switch (operator) {
case '+' -> num1 + num2;
case '-' -> num1 - num2;
case '*' -> num1 * num2;
case '/' -> (num2 != 0) ? num1 / num2 : Double.NaN;
default -> {
System.out.println("Invalid operator!");
yield 0;
}
};
console.printf("Result: %.2f%n", result);
}
}
Why use Console?
Best for secure input (e.g., passwords, sensitive data).
Works well in command-line applications.
Note: It won’t work in some IDEs like Eclipse because they don’t support
System.console()
.
So, which method should you choose?
- If you need simplicity → Use
Scanner
. - If you need speed for large inputs → Use
BufferedReader
. - If you need security for sensitive inputs → Use
Console
.
Hope this helps! Let me know if you need any improvements in your calculator!