November 2nd, 2013, 02:47 AM
While loop with if..else and exceptions
I am having trouble getting some code to work properly if anyone could help me I would appreciate it.
I am looking for this to display a window to collect user input.
Currently it will work if I enter "small" but it keeps throwing the IllegalArgumentException and goes back to the question as it should with any other input. So what I am looking for is to be able to store small, medium, large or xlarge in the gloveSize variable depening on which option the user inputs.
I am sure this is not the best way to right this code, however this is the requirement for the project right now.
String gloveType ="";
boolean gloveTypeOK = false;
while (! gloveSizeOK)
gloveSize = JOptionPane.showInputDialog(gloveMsg2);
throw new NullPointerException();
if(! gloveSize.equalsIgnoreCase("Small") || gloveSize.equalsIgnoreCase("Medium")
|| gloveSize.equalsIgnoreCase("Large") || gloveSize.equalsIgnoreCase("XLarge"))
throw new IllegalArgumentException();
gloveSizeOK = true;
}// end try
} // end catch
String errorMsg = String.format("%s is invalid. Enter Small, Medium, Large, XLarge", gloveSize);
} //end catch
} //end while
November 2nd, 2013, 05:46 AM
Is that from inside the big if statement? What is the value of gloveSize that causes the exception to be thrown? The if statement is true for that value.
Please edit the post and wrap the code in code tags.
November 2nd, 2013, 07:48 AM
NormR Thank you for your reply
This statement was enough for to catch my error.
Originally Posted by NormR
Here is the fix that I came up with.
if(! (gloveSize.equalsIgnoreCase("Small") || gloveSize.equalsIgnoreCase("Medium")
|| gloveSize.equalsIgnoreCase("Large") || gloveSize.equalsIgnoreCase("XLarge")))
November 2nd, 2013, 08:11 AM
Yep.. The properly enclosing ()s fixed it.