# Simple code but very confused

• 10-07-2012, 05:41 AM
Faytrow
Simple code but very confused
Okay, so my code is

if (input.equalsIgnoreCase("one") || input.equalsIgnoreCase("uno") || Integer.parseInt(input) == 1) {
x = 1;
} else if (input.equalsIgnoreCase("two") || input.equalsIgnoreCase("dos") || Integer.parseInt(input) == 2) {
x = 2;
} else if (input.equalsIgnoreCase("three") || input.equalsIgnoreCase("tres") || Integer.parseInt(input) == 3) {
x = 3;
} else {
x = -1;
}

I'm trying to make it so if you type 1, "One", or "Uno" it sets X to 1, same with 2, "two", "dos" makes X = 2 and 3, "three", "tres" makes X = 3. Then following is a switch statement that does case 1, 2, or 3 depending on what X is.

For some reason though, "two", "dos", "three", and "tres" cause an error that reads

Exception in thread "main" java.lang.NumberFormatException: For input string: "two"
at java.lang.NumberFormatException.forInputString(Num berFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at lab04.Lab04.main(Lab04.java:22)
Java Result: 1

Does anyone know what is causing this? and also if I made any mistakes in posting this, please let me know. Thanks a lot! :)
• 10-07-2012, 05:52 AM
Fubarable
Re: Simple code but very confused
The problem arises when your code tries to parse the String as an int and no int is present. This will cause a NumberFormatException to be thrown. If you're going to do this in this way, you'll need to wrap the code that parses the int in a try/catch block that catches NumberFormatException and then ignore the exception. Perhaps a better way to do this is to see if the String equals("1"), and the same for other numbers.

As for mistakes, no, no mistakes, but your posted code will be easier to read if you use code tags. Please read the link in my signature about these.
• 10-07-2012, 05:57 AM
Faytrow
Re: Simple code but very confused
Okay, that makes sense. Why does "One" and "Uno" work though? That's mostly what threw me.
• 10-07-2012, 06:00 AM
Fubarable
Re: Simple code but very confused
Quote:

Originally Posted by Faytrow
Okay, that makes sense. Why does "One" and "Uno" work though? That's mostly what threw me.

This brings up a very good learning point. Both || and | work as logical or operators, but || will shortcut if one of its boolean tests is true. In other words, if the text is "one" or "uno", as soon as the equalsIgnoreCase(...) evaluates to true, the || operator stops further checking and simply returns true. So the Integer.parseInt(...) is never called.
• 10-07-2012, 06:27 AM
DarrylBurke
Re: Simple code but very confused
Please go through the Forum Rules -- particularly the third paragraph.

db