Obtaining Command Line Input in Java

Brandon Rozek

August 28, 2017

To obtain console input for your program you can use the Scanner class

First import the relevant library

Then create a variable to hold the Scanner object

Inside the parenthesis, the Scanner binds to the System input which is by default the console

The new varible input now has the ability to obtain input from the console. To do so, use any of the following methods

<th class="tg-yw4l">
  What it Returns
</th>
<td class="tg-yw4l">
  The next space seperated string from the console
</td>
<td class="tg-yw4l">
  An integer if it exists from the console
</td>
<td class="tg-yw4l">
  A double if it exists from the console
</td>
<td class="tg-yw4l">
  A float if it exists from the console
</td>
<td class="tg-yw4l">
  A string up to the next newline character from the console
</td>
<td class="tg-yw4l">
  Returns true if there is another token
</td>
<td class="tg-yw4l">
  Unbinds the Scanner from the console
</td>

Here is an example program where we get the user’s first name