System In, Out, and Error

Standard-In

Programs often need additional information from users and this information is often entered in via the keyboard. This is so prevalent that most programming languages have a pre-established input channel, called standard-in. By default, when a user types a character on the keyboard, the character is written to standard-in. The program, when it is ready, can then read in the characters.

In Java, this channel is called System.in. It’s often helpful to use a helper class named Scanner when we know the types of data that will be entered into the keyboard. ┬áThe scanner class returns tokens that are separated by some delimiter. By default the delimiter is any whitespace (e.g. space, newline, tab).

Some of the methods provided by the Scanner class are next(), hasNextInt(), nextInt() and nextLine().

Here is an example of how Scanner can be used to read in two integers.

Scanner sc = new Scanner(System.in);

int a = sc.nextInt();
int b = sc.nextInt();
int sum = a + b;

System.out.println("sum = " + sum);
sc.close();

When nextInt() is called, it waits until an integer is entered into the keyboard. Once the user types in a number and presses enter (whitespace), the program moves to the next call to nextInt().

If you want to read individual characters off the scanner’s stream you have to change the scanner’s delimiter to the empty string as shown below.

sc.useDelimeter("");

Standard-Out

We’ve already seen how we can write to the console using println().

System.out is a PrintStream object and has many other methods for us to play with.

As we know, println() prints the string passed into it followed by a newline character. If we want to print a single value without the newline character you can use the print() method.

Another method that is very useful is printf(String format, Object ... args). The first argument is a string that can contain placeholders, characters and escape sequences. The placeholders begin with % and are followed by characters which indicate what type of value will be later put in its place. The variable list of args are variable names whose values replace the placeholders when the string is printed.

Below are some examples.

String name = "Gigi";
int count = 3;
char grade = 'A';
System.out.printf("%s received (%d) %c's.\n", name, count, grade);

When run, the following would appear on the console.

Gigi received (3) A's.

Standard-Err

When debugging your code you may want to print data to the screen, but don’t want that data to be sent to System.out. For example, debug messages that are sent to System.out will be marked as incorrect by Kattis.

In this case, you can print those debug messages to System.err in the same way that you would to System.out. They won’t be read by Kattis but will appear in the console.

© 2017 – 2019, Eric. All rights reserved.