Java: How to get input from System.console()
To get input from the System.console()
in Java, you can use the readLine()
method of the Console
class. Here's an example of how to use readLine()
to read a string from the console:
import java.io.Console;
public class Main {
public static void main(String[] args) {
Console console = System.console();
if (console != null) {
String name = console.readLine("Enter your name: ");
console.printf("Hello, %s!\n", name);
}
}
}
The readLine()
method prints the prompt string to the console and waits for the user to enter a line of text. When the user presses Enter
, the text they entered is returned as a string.
You can also use the readLine()
method to read other types of data, like integers or booleans, by parsing the input string. Here's an example of how to read an integer from the console:
import java.io.Console;
public class Main {
public static void main(String[] args) {
Console console = System.console();
if (console != null) {
String input = console.readLine("Enter a number: ");
int number = Integer.parseInt(input);
console.printf("The number you entered is %d\n", number);
}
}
}
Note that the System.console()
method may return null
if the Java virtual machine is running in a context where there is no console, such as when running in an IDE. In this case, you can use a different method to get input from the user, like Scanner
or JOptionPane
.