Trying to Read from the Console in Java

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

Reading and writing to console in Java

Java 1.6 has a Console class that simplifies some things. In general, System.out and Scanner on top of System.in are usually enough.

Don't get result when I try to read console output error in java

if you want to write the output of an Exception into a file, you have to mention that in the catch() block. (if you have multiple catch blocks, you can create a method that contains the writing process and call it each time, to avoid repeating the same code each time )

try
{
//... some code...
}
catch (Exception e)
{
FileWriter myWriter = new FileWriter("Error.txt",true);
PrintWriter pw = new PrintWriter (myWriter);
e.printStackTrace (pw);
System.out.println("Successfully wrote to the file."); //this will be only shown in the console,
// but never printed in the file
}

this way, you no longer need the code that you provided which is totally wrong. you can just remove it

NumberFormatException when trying to read dates from console input

There are two reasons for the NumberFormatException here:

1.You have multiple spaces in your input between the day, month and the year.

2. Scanner's nextInt does not consume the newline. Hence you need to include a dummy nextLine after it. You can read more about this here.

int num = in.nextInt();
in.nextLine(); //To consume the new line after entering the number of dates
System.out.println("Enter " + num + " dates: ");

String [] dates = new String[num];
...


Related Topics



Leave a reply



Submit