Class 1: Handling Console Input

So, now that we can setup 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.

<pre><code>import java.util.Scanner</code><pre>

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

<pre><code>Scanner sc = new Scanner(System.in);</code></pre>

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

<pre><code>String aString = sc.nextLine();</pre></code>

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

Notice the <code>nextLine()</code> method. <code>nextLine()</code> reads the entire line of console input as opposed to using <code>next()</code> 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.

<pre><code>String bString = sc.next()</pre></code>

Then if the user were to type in <pre><code>Hello World!</code></pre>, bString will only be <pre><code>Hello</code></pre> instead of 

<pre><code>Hello World!</code></pre>. If we actually wanted to get the subsequent words, we would have to make set new strings to handle 

<code>next()</code> 

<pre><code>String bString = sc.next()</pre></code>

So now, 

<pre><code>bString</pre></code> will now be equal to <pre><code>World</pre></code>. If the user only entered 

<pre><code>Hello</pre></code>, 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.

<pre><code>sc.close()</pre></code>

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 walk through and the other is a really simple implementation of a super awesome and original game, Angry Libs that I just thought of.

Input Fun – Walking through using the Scanner Object. Github Code.

Angry Libs – The totally original kids game that I totally made. Github Code.


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.

Advertisements