metacontent
metacontent

Reputation: 1356

Parsing java main args[] array errors

Hello I'm stuck on a simple Java exercise, I hope someone can help.

Sorry if this is really simple I'm a java newbie.

What I'm having trouble with: if the user enters a string other than "help" such as "foo" then I get the following error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "foo"

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)

at java.lang.Integer.parseInt(Integer.java:447)

at java.lang.Integer.parseInt(Integer.java:497)

at NumberGuess.main(NumberGuess.java:10)

What I think is happening: "foo" is not being caught by "else" because args[0] is an object reference and not really a string.

What I want to know: How to catch everything other than "help" or the numbers "1" to "5"?

Here is the code...

public class NumberGuess {

public static void main(String args[]){

    int r;
    int g;

    if ((args[0].compareTo("help")) == 0){
        System.out.println("Enter a number between 1-5 to play.");
    } else if (Integer.parseInt(args[0]) > 0 && Integer.parseInt(args[0]) <= 5){

        r = ((int)(Math.random()));
        g = Integer.parseInt(args[0]);

        if (r == g){
            System.out.println("YOU WON!");
        } else {
            System.out.println("Wrong: number was " + r);
        }

    } else {
        System.out.println("Something went horribly wrong.");

    }}}

Upvotes: 0

Views: 6994

Answers (4)

Bill K
Bill K

Reputation: 62769

The first thing it does after looking for "Help" is trying to parse it as a number:

g = Integer.parseInt(args[0]);

What you can try to do is catch this exception by changing that line to:

try {
    g = Integer.parseInt(args[0]);
} catch(NumberFormatException e) {
    System.out.println("The first parameter was supposed to be a number!");
    System.exit(1);
}

If you meant to accept parameters like "foo 1", then you should be parsing args[1] as the number, and args[0] you should test to see if it's "foo" like this:

if(args[0].equalsIgnoreCase("foo")) {
    // now we know foo is the first arg.  Parse args[1]!
    ...
} 

Oh, by the way. "Random" numbers in most languages are a number between 0 and 1. They generally look like ".108937190823..."

If you want to check for a number like 1-10, you need to do something like this:

Random().nextInt(10) + 1;  // (Thanks @mmyers)

(Not totally sure that's the right way to do it, but it's close.

Upvotes: 1

Alex Martelli
Alex Martelli

Reputation: 881575

As you've noticed, parseInt raises an exception if you try to parse a string that doesn't correctly represent an error; try/catch is the Java construct for catching such exceptions and dealing with them -- look it up in your favorite Java docs!

Upvotes: 0

Vini
Vini

Reputation: 8419

What is happening here is that the code goes in the else block (as you guessed) and the else block straight away tries to convert the parameter into a number (Integer.parseInt(args[0]). So, you can add a try catch block for handling such scenarios:

public class NumberGuess {

public static void main(String args[]){

    int r;
    int g;
    int temp;

    if ((args[0].compareTo("help")) == 0){
            System.out.println("Enter a number between 1-5 to play.");
    } else {
            try{
                temp = Integer.parseInt(args[0]);
            }catch(NumberFormatException e){
                System.out.println("Please enter a number");
                System.exit(-1);
            }
            if (Integer.parseInt(args[0]) > 0 && Integer.parseInt(args[0]) <= 5){
            r = ((int)(Math.random()));
            g = Integer.parseInt(temp);

            if (r == g){
                    System.out.println("YOU WON!");
            } else {
                    System.out.println("Wrong: number was " + r);
            }
            }

    } else {
            System.out.println("Something went horribly wrong.");

    }}}

Here's is one way you could write the code (just a suggestion).

Upvotes: 1

erickson
erickson

Reputation: 269657

The program logic is essentially, "if argument zero is not 'help', parse it as an integer…" At that point, the exception is thrown, because "foo" is not a valid integer.

The simplest approach is to catch the NumberFormatException and print a more helpful message.

if ("help".equals(args[0])) {
  System.out.println("Enter a number between 1 and 5 to play.");
}
else {
  int number;
  try {
    number = Integer.parseInt(args[0]);
  }
  catch (NumberFormatException ex) {
    System.out.println("Input is not an integer: " + args[0]);
    return;
  }
  if ((number < 1) || (number > 5)) {
    System.out.println("Number out of bounds: " + number);
    return;
  }
  int r = new java.util.Random().nextInt(5) + 1;
  if (number == r)
    System.out.println("You won!");
  else
    System.out.println("You lost!");
}

Upvotes: 3

Related Questions