Skip to main content

Class 1: Handling Console Input


(Updated: )

Note: This post has been moved from an older blog. Don’t learn Java from here, check out this Java Programming tutorial by Derek Banas instead.

So, now that we can set up a java file, let’s move onto taking console input. While it’s nice just to run programs without user input, more often than not, we will need to take input from users and do stuff with it. The simplest way to do this is through the Scanner Object.

The Scanner Object allows a program to accept input in the form of text, such as a file, a string, or in this case, the console. In order to do this, we need to import the module containing the scanner object at the top of the file.

import java.util.Scanner

Once that had been done, you will need to set up the default template just like the Hello World Example. Once that has been done, we can declare the scanner object like this:

Scanner sc = new Scanner(System.in);

To actually take input, you create a new variable and set it to equal the next line input.

String aString = sc.nextLine();

To print it out, just do the ordinary System.out.println(aString);

Notice the nextLine() method. nextLine() reads the entire line of console input as opposed to using next() which reads just the information until a white space (one word) or some other pattern, known as a delimiter. So if we typed this to get the next word.

String bString = sc.next();

Then if the user were to type in Hello World!, bString will only be Hello instead of Hello World! If we actually wanted to get the subsequent words, we would have to make set new strings to handle next().

String bString = sc.next();

So now, bString will now be equal to World. If the user only entered Hello, another prompt would appear. If the user entered something longer, another user prompt will not appear until Java can no longer assign a variable to a String.

Once we’re done using the scanner (usually with files), we need to close the scanner like so.

sc.close();

And that’s how we use Scanner Object. I’ve made two examples showing how to use the scanner object, one is more of a walkthrough and the other is a really simple implementation of a super awesome and original game, Angry Libs that I just thought of.

Sample Projects


Footnote: No, it’s not actually my idea. Also, sorry about all the <pre> tags, I don’t know how to display code blocks and Tumblr is really hard to work around. I fixed those on January 30, 2019, when I moved to a new personal website.