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.");
}}}