# Thread: Simple code but very confused

1. Member
Join Date
Oct 2012
Posts
7
Rep Power
0

## 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! :)

2. ## 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.

3. Member
Join Date
Oct 2012
Posts
7
Rep Power
0

## Re: Simple code but very confused

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

4. ## Re: Simple code but very confused

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.

5. ## Re: Simple code but very confused

Please go through the Forum Rules -- particularly the third paragraph.

db

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•