Java Command Line Apps In 15 Minutes (Or Less)

In my first four college classes on object oriented programming, every assignment had us prompting the user for input from the command line.  After the third assignment, I figured out this shortcut, and aced every assignment after that.

With this great power comes my great responsibility to share it with those who come after me.

But before I get too far into this, you should also know that in my professional career, I’ve never had to do this. Ever. EVER!

Static Classes Are Your Friend

While most of my classmates were new to programming, I had an advantage.  College was not my first programming rodeo.

Clown Dies in Second Rodeo
It wasn’t my second rodeo, either.

So I decided to use my forbidden knowledge of static classes to my benefit!

I started with this simple static class which I called CommandLine (but feel free to rename it to whatever suites you) and a method that took a string argument, printed it out, and returned a string that represented the users response.

[code language=”java”]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CommandLine
{
private static final BufferedReader input;
static
{
input = new BufferedReader(new InputStreamReader(System.in));
}

private CommandLine() {};

public static String getUserInput (String message)
{
System.out.print(message);
String value = null;

try
{
value = input.readLine();
}
catch (IOException e)
{
//TODO : Handle error as appropriate
}

return value;
}
}
[/code]

Don’t Repeat Yourself

Sometimes, the data I needed from the user had to be a certain length. Other times, the data had to be an integer in a certain range. Still other times, I just needed a Y/N or  T/F.

And since we all know what a bad idea it is to repeat yourself…

Not technically repeating, more of a daily refactoring...
Not technically repeating, actually more of a daily refactoring…

So I reused what I had by adding to my static class every time a new situation for user input validation arose.

When I needed a string that was no more than some arbitrary number of characters long:

[code language=”java”]
public static String getUserInput (String message, int maxLen)
{
boolean loop = true;
String value = null;

while (loop)
{
loop = false;
value = getUserInput(message);
if (value.length() > maxLen)
{
loop = true;
System.out.println();
System.out.println("Input must be less than " + maxLen + " characters.");
}
}

return value;
}
[/code]

When I needed an integer in a given range:

[code language=”java”]
public static int getNumberInRange(String message, int min, int max)
{
boolean loop = true;
int value = 0;

while (loop)
{
loop = false;
String input = getUserInput(message);
value = Integer.parseInt(input, 10);

if ((value > max) || (value < min))
{
loop = true;
String alert = (value > max) ? "Value must be less than or equal to " + max : "Value must be more than or equal to " + min;
System.out.println();
System.out.println(alert);
}
}
return value;
}
[/code]

When I needed a boolean (Y/N or true/false):

[code language=”java”]
public static boolean getUserInput (String message, String tv)
{
String value = getUserInput(message);
return (value.equalsIgnoreCase(tv)) ? true : false;
}
[/code]

Every new project started with me copying this class into it.

Getting user data from the command line in Java? Problem solved!

There was a spider, I panicked. [House burning down] But I think it's gone now.
Another problem solved! Man, I’m on a roll today!

Why Didn’t You Use java.util.Scanner?

There is always more than one way to do it. But the simple truth is that it wasn’t around back then.

So, now that it is, why didn’t I just use it in this example?

From the java.util.scanner docs: A simple text scanner which can parse primitive types and strings using regular expressions.

First, this post is intended for people who are new to Java, and likely new to OO and/or programming in general.  Let’s not muddy the waters for them with regular expressions right off the bat.

Second, one needs to understand the difference between Scanner and BufferedReader.

  • Scanner is a single token input system that uses white spaces as the default delimiter.
  • BufferedReader is a buffered input system. It takes a stream of data and then feeds it into the data type that I specify.

In our example here, we want all the data the user typed up until the enter key was hit.  BufferedReader is our winner!

You win...*this* time.  I'll get you next time, BufferedReader.  Next time!!
You win…*this* time. I’ll get you next time, BufferedReader. Next time!!

As always, you can grab the code from my gist here.

One thought on “Java Command Line Apps In 15 Minutes (Or Less)”

Leave a Reply

Your email address will not be published. Required fields are marked *