Java Lesson 6: Simple Console Input / Output

3
39

Introduction

Until now, we have considered only internal program operations, and have assumed that the input data is assigned to variables somehow and that the println() method transformed the data into readable form. We shall now consider the input/output statements that handle these functions. This will enable us to write more useful and complex programs.

About Console Input / Output

Picture of a hardcopy terminal.
Digital Equipment Corporation DECwriter hardcopy terminal.

Long before there were graphical user interfaces (GUIs) and mouse devices, hardcopy console terminals resembled typewriters or TV screens that could only display black and white letters and numbers. Most operating systems still support console input/output (I/O) for two reasons:

  1. Some advanced system commands can only be performed from the console command prompt interface.
  2. Mouse and GUI operations require advanced programming skills which we have not covered yet.

Real-world applications are rarely text-based console programs, but are GUI-based apps that rely on Java’s Abstract Window Toolkit (AWT) or Java Swing, or they are web applets. In this lesson we will learn about methods that Java provides for console I/O which are suitable for instructional purposes. Interestingly, the same techniques used for console I/O are also used for file I/O and network I/O, so the fundamentals we learn here will apply in future lessons. You will be using your Windows Command Prompt application (Start > All Programs > Accessories > Command Prompt) or Linux / Mac Terminal application to enter input, just like you have been to compile and run Java programs in these lessons. The Java compiler requires import statements at the beginning of the program to define classes and methods used for subsequent I/O operations. Then, I/O can be performed anywhere within a program using the techniques described below.

Streams

Picture of data flow to and from a computer.
Data flow to and from a computer.

Java programs perform I/O through streams, which either produce or consume information. You can think of streams as a stream of water that either carries information to the computer or out of the computer. A stream connects to a physical device like a keyboard, a display, a printer, a disk file, or a network. The same I/O classes can be used for any type of device.

Console Input

Compared to other programming languages, Java excels at making common tasks difficult, like getting input from the user. One reason for this is that unlike other languages (eg. BASIC), Java does not have an INPUT or READ statement. Instead, Java relies on classes and methods to achieve the same result. A benefit of this approach is that there are several ways to accomplish data input, and you as a developer can write your own custom routines.

We will examine the Scanner class. Scanner is used to read input from the console or a file. This class and its associated methods allow a user to enter data into a program while the program is run, rather than at compile time as in the previous example programs. This makes the program more flexible and useful. Such programs can be written by one person and used by another person who enters the data that the program acts upon. Two lines of code are needed before we can actually read input from the console. First, an import statement informs the Java compiler that the Scanner class is used by a program.

Then create a new instance of a Scanner for the keyboard.

We will use the variable kb when getting input, although you can name the variable anything you want. If you have a background in the C language, you may be more comfortable naming it stdin (simply replace all occurrences of kb with stdin in the following programs.

The nextLine() method reads a line of input from the user.

Program6a.java is a simple program which uses the Scanner class to get a line of input from the user. Enter (or copy and paste) this program to your computer, then compile and run it.

When the program runs, it prompts the user to enter some text. The user’s input is stored in the string variable line, and then displayed back to the user. Screenshot of compiling and running Program6a The user can enter any characters(s), including letters, punctuation, and/or numbers. However, any numbers are treated as part of a String, and not as numbers that could be operated on numerically.

Numeric Entry With nextDouble()

The nextDouble() method reads a number of type double from the user.

The Java Library contains many more methods, such as nextInt, nextByte, nextLong, nextShort, and so on for other data types. Program6b.java is another simple program which uses the Scanner class to get a number of type double from the user.

When Program6b runs, it prompts the user to enter a number. The user’s input is stored in the variable num, and then displayed back to the user.

We now have enough knowledge to write a useful program. Program6c calculates how much interest is earned after one year. Instead of hardcoded values for the principal (the initial amount of money invested) and the yearly interest rate, we allow the user to enter whatever parameters they wish. The program is flexible because the user can run the program several times with different values.

In the screenshot below, the user entered an initial investment of $3875.46, and an interest rate of 2% (0.02). Note that a currency symbol (e.g., $, €) must not be entered because it is a character, not a number. The program calculated that the user will have a total of $3952.9692 after one year. Screenshot of compiling and running Program6c. At this point you should enter and run the program on your computer, using several different values to see what your investment will become under different scenarios.

Numeric Entry With next() and Double.parseDouble() or Integer.parseInteger()

Java often has many ways to accomplish the same result. Another way we can acquire a numeric value from the user is to accept the entry as a String with the next() method (instead of nextDouble() or nextInt()), and then convert the String to the desired data type such as integer, double, short, long, byte. We will examine two methods: Integer.parseInt() and Double.parseDouble(). Program6d.java reads all input as a String, and then uses the appropriate parse method to convert it to a number.

Screenshot of compiling and running Program6d

Data Validation to Prevent Exception Errors

If you ran any of these programs you may have seen a stack trace like the one shown below. Problems occur when the user enters “invalid” values. For example, if the program expected a number and inadvertently received characters, then an exception is raised which causes the program to be stopped abruptly. In the next lesson Conditionals and in the Exceptions lesson we will discover how to validate the user’s input and gracefully handle this possibility with more robust code. Screenshot of incorrectly entering characters instread of numbers.

Console Output

Displaying results on the console is relatively straightforward; in fact, we’ve done it all along with System.out.print() and System.out.println() method calls. The difference between the two methods is that println() appends a carriage return and linefeed (collectively called a newline) to the end of the output text so that the cursor automatically goes to the beginning of the next line, whereas print() does not append these characters. You may have several print() statements in a sequence, usually followed by a println(). For example, the code fragment:

will display:
to be or not.

Formatting Console Output

Consider this program which calculates the value of an investment over several years.

Running Program6e which displays unattractive output. This program’s output is functional, but not particularly attractive. The columns do not line up, there are too many digits displayed after the decimal point, and it kind of runs together. The output can be visually enhanced. Additional whitespace makes output easier to read. It may be beneficial to have numbers line up neatly in columns like in a spreadsheet. You may also have noticed that the answer was displayed as “$9972.288”, even though currency amounts are usually displayed with two digits after the decimal point. The following techniques will allow you to style your output in a user-friendly fashion.

  • Extra System.out.println() statements can create whitespace around your output.
  • The escape sequence “\n” in a System.out.print() or System.out.println() statement will add an extra newline (carriage return and linefeed) to the output text.
  • The escape sequence “\t” in a System.out.print() or System.out.println() statement will add a tab character to the output text. This is useful to indent or align text into readable columns.
  • The Formatter class and its methods let you display numbers, dates, and strings in several different formats. It’s purpose is similar to the PRINT USING statement in BASIC, or printf() in C and C++.

The following table lists some useful format specifiers and their purpose:

 Format Specifier  Purpose and example usage
 %b Boolean.

System.out.printf(“Truth is %b”, !false);

%c Character.

System.out.printf(“One character %c”, ‘A’);

%d Decimal integer number.

System.out.printf(“Pod of %d narwhal whales.”, 8);

%<w>d Decimal integer number with a minimum width of w spaces.

System.out.printf(“Pod of %4d narwhal whales.”, 8);        // Width is at least 4 spaces.

%e Scientific notation.

System.out.printf(“Large number is %e”, 6002214.8474);

%f Decimal floating point number.

System.out.printf(“%f km per hour”, 8473.27);

%<w.w>f Decimal floating point number with a minimum width of w.w spaces.

System.out.printf(“%8.1f km per hour”, 8473.27);      // Width is 8 spaces with 1 after the decimal.

 %n Insert a newline character.

System.out.printf(“A newline appears %n here”);

%s String.

System.out.printf(“Insert the %s here”, “word”);

%% Insert a percent sign.

System.out.printf(“Your score is %d%%”, 99);

Left justification.

System.out.printf(“%-8.1f km per hour”, 8473.27);

, Numeric values include grouping separators.

System.out.printf(“%,8.1f km per hour”, 8473.27);

( Enclose negative numeric values in parenthesis.

System.out.printf(“Income or (loss) to date: %(8.2f”, -10000.00);

Let’s use these in Program6e.java to demonstrate their use.

Running Program6eFormatted with attractive output.The user can immediately see a stylistic improvement. A generous use of whitespace and tabs makes it clear where the user must enter values. Right-aligning the year and currency amounts format the columns. The currency has grouping separators (commas), and is truncated to two digits after the decimal point.

Summary

The information in these first six lessons is enough to enable you to write simple but complete programs, including inputting data and the printing out of results. In the next few lessons we shall introduce several control statements which will allow you to write more involved programs.

Next Lesson

Next we will move on to Conditionals.

 

3 COMMENTS

  1. […] Lesson 6 Console I/O where we learned how to use the Scanner class to read user input from the keyboard. […]

  2. […] in Java tutorial Lesson 6: Simple Console Input / Output, we used the Scanner class to get input from the user as a text String and convert it to a number […]

  3. […] Java Lesson 6: Simple Console Input / Output, we learned ways to receive user input from the keyboard and output information to the display […]

Leave a Reply