Java for Humans {Input & Output (I/O)}

Lincoln W Daniel
Jan 17, 2016 · 6 min read
View Table of Contents | Download Supporting Code | Subscribe to ModernNerd Youtube Channel for Coding Videos | By Lincoln W Daniel

Remember, from the Variables chapter, that we program to capture and manipulate information, or data, to create new data for users to consume. Software programs would not be interesting without being able to capture information, accept input from the user and produce new information — create output for the user to consume.

As a kid, you likely played games that asked for your name and age and used that information to tailor your experience to you. To tailor the gaming experience to you, games usually refer to you by your name and use your age to determine which parts of the game would be most appropriate to show you. In some cases, games may not let you play if you provide an age that is too young. This is all an example of gathering user input and using it to create output for the user. In this chapter, we will learn how Java allows us to easily gather input and produce output in our programs.

Scanning User Input from Keyboard

From the very beginning of the book to now, we’ve been using Java’s Scanner class to capture input from the user. The Scanner class allows you to read input available from an input stream. An input stream simply holds data coming in to your program while an out stream holds data going out of your program. In previous chapters, our input stream has been System.in, which streams in data from the user’s keyboard.

The “System” is the current system your program is running on. System is a class provided by Java. Notice that we didn’t need to create a new instance of System in order to access its in static InputStream field. This is a prime example of the utility of static fields.

The Scanner’s constructor takes a Java InputStream object as its single argument in order to create a new instance of a Scanner:

Scanner scanner = new Scanner(System.in);

With our new Scanner instance, we can read user input from the user’s keyboard because we provided it in as the InputStream. The Scanner class has many useful instance methods that allow us to check if there is input available in the provided input stream and to read available input into our program.

Checking for Input

Before reading input from a Scanner instance, it’s smart to check if there is actually input available to read. Like you would check if your bank account has money in it before you try to withdraw money from it, we always make sure our scanner has valid data ready for reading before trying to read from it. The hasNext() instance method returns true only if there is data available in the provided InputStream object to read. If there is no data ready for us to read, the hasNext() method returns false:

if(scanner.hasNextLine()) {
//new line of data is available in input stream
//read from the scanner
} else {
//no line of data available in input stream
//don't read from the scanner
}

The Scanner class also has instance methods for checking if the provided InputStream object has data of a certain type available for reading. We can check if there is an int, double, long, boolean, and other data types available for reading. Each datatype has its own hasNext method; you can check for an int by calling hasNextInt() on the scanner:

if(scanner.hasNextInt()){
//read the int from the scanner
} else {
//scanner does not have an int ready for reading
}

Reading Input from Scanner

Now that we know our user has typed something into their keyboard and that input is stored in the InputStream object provided to our scanner, we can read it into our program. To read data from the scanner, we can simply call the next() instance method to get the next data token available in the scanner. Further, if we want to read the entire next line of data available in the scanner, we can call the nextLine() instance method:

if(scanner.hasNextLine()) {
String nextLineOfData = scanner.nextLine();
}

Like the hasNext() method, the next() method has special methods to read only the next token of data of a specific type; the nextInt() method will read and return the very next integer that is available in the scanner’s input stream:

int nextIntInScanner = scanner.nextInt();

Outputting Data to the Console

System.out.print("This string will be printed to the console through the OutputStream instance stored in System.out\n");

Java allows us to create output to the console by accessing the static out field of the System class. The out field is a PrintStream instance and also, by inheritance, an OutputStream instance, so it allows us to print data out of our program. In this case, we are printing data out to the console by calling the out field’s print() instance method. The print() method takes a single argument, the String instance to be printed, and prints it to the console inline. If we want to print data on a new line each time, we can call the println() instance method which adds a new line character (‘\n’) to the front of the string we want to print.

The new line character adds a new line to the output wherever it’s placed in a string and we can use it as many times as we want to separate different lines of our output.

Continuously Reading Input from Scanner

When you play a game, it doesn’t simply ask you for your information, read it, and end. The game uses the information you give it and continues running until you decide to end it. We can do this in Java by continuously reading user input while it is available and the user has not asked to end our program. We do this by using a while loop and some logic. Let’s ask the user for her name and age and decide whether or not to let her play our game. If she is old enough, we will let her know she can play our game and then ask her if she wants to exit or play again:

String userInput = "";
while(!userInput.equals("exit")) {
String userName = "";
int userAge = 0;
System.out.println("Enter your name to begin: ");
if(scanner.hasNext()) {
//get the user's name from the scanner
userName = scanner.next();
}

System.out.println("Enter your age: ");
if(scanner.hasNextInt()) {
//get the user's name from the scanner
userAge = scanner.nextInt();
}
/*check the user's age
to make sure she's at least 13 years old*/
if(userAge >= 13) {
System.out.println("Hi " + userName );
System.out.println("You are old enough to play our game!");
//TODO: write code to play fun game here

System.out.println("Game over!");

System.out.println("Enter YES to play again or EXIT to exit.");
if(scanner.hasNext()) {
userInput = scanner.next().toLowerCase();
}
} else {
System.out.print("\n\nYou're too young to play this game. Ending...");
break;
}
}

Notice that we take in the user’s name and age to begin the game. Before we start, we let the user know what’s expected of them and what’s going on throughout the game by creating output when necessary through System.out.

Input and output are necessary for many programs and they allow us to add more interactivity our programs. You are now equipped with all you need to know about input and output to begin making your programs more dynamic. Play around with the code to see what else you can do with input and output.

Inheritance Primer

Earlier in this chapter, I said that out is an OutputStream and a PrintStream instance at the same time. By that, I meant that out is an instance of the PrintStream which inherits fields and methods from its super class, the OutputStream class. We will learn more about inheritance and class extension soon, but for now, just know that a PrintStream is an Outputstream. If you had some trouble at that point, don’t worry, we’ll touch on it again soon.


ModernNerd Code

Learn to Code Life. Subscribe to Video Tutorials on Youtube

Lincoln W Daniel

Written by

My passion is in developing software to enable people to accomplish their goals more efficiently. Author @JavaForHumans.com. Creator of @Smedian.com

ModernNerd Code

Learn to Code Life. Subscribe to Video Tutorials on Youtube

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade