Get input from console in java
49, 52, and 10 are the ASCII character codes for the characters you typed, 14Enter.
You may continue to use System.in.read()
, and process each character as it arrives. You would do something like the following:
- collect the characters that are typed
- look for digits typed followed by Enter
- convert the ASCII codes of the digits to a decimal number
This is, of course, exactly what Scanner.nextInt()
does for you.
What's the best way to get console-input in Java?
I think, The scanner class is quite helpful.
For example with BufferedReader, you have to read a line at a time and parse it for the values.
But in the scanner you get integers with nextInt() method etc.
How to send input to System.console.readLine(...) in Junit?
I got this to work using JMockit to mock the Console class:
@Test
public void test(
@Mocked final System systemMock,
@Mocked final Console consoleMock) {
new NonStrictExpectations() {
{
System.console();
result = consoleMock;
consoleMock.readLine(anyString);
result = "aUsername";
consoleMock.readPassword(anyString);
result = "aPassword";
}
};
MyClass.main(null);
}
How can I read input from the console using the Scanner class in Java?
A simple example to illustrate how java.util.Scanner
works would be reading a single integer from System.in
. It's really quite simple.
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
To retrieve a username I would probably use sc.nextLine()
.
System.out.println("Enter your username: ");
Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();
System.out.println("Your username is " + username);
You could also use next(String pattern)
if you want more control over the input, or just validate the username
variable.
You'll find more information on their implementation in the API Documentation for java.util.Scanner
Related Topics
Classcastexception When Casting to the Same Class
Is the Order of Values Retrieved from a Hashmap the Insertion Order
Add Buttons to Tabs and Tab Area Javafx
Android Studio Google Jar File Causing Gc Overhead Limit Exceeded Error
Android Camera Will Not Work. Startpreview Fails
Kiosk Mode for Linux Java Swing Application
Find the Pid of a Java Process Under Linux
Java's 'Tnameserv' Takes 3+ Minutes to Be "Ready", Why
Java Installation Issues on Ubuntu
Variable Column Names Using Prepared Statements
Java Switch Statement: Constant Expression Required, But It Is Constant
Get Battery Level and State in Android
How to Get the First Day of the Current Week and Month
How to Set Java_Home Path on Ubuntu
Why Stringbuilder Stops Adding Elements After Using the Null Character