Java: How to Get Input from System.Console()

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



Leave a reply



Submit