|
Hello and thanks for taking a look at my problem.
I am somewhat a beginner and I'm working on a program for fun that builds a maze and lets the user navigate through it by entering an integer to indicate which direction they want to move (through a 2D array).
My problem is this:
In an input box I have it printing what can be seen so far of the maze and gives options that look like this:
Which direction would you like to go?
8 = north
6 = east
4 = west
2 = south
I get the input from a:
String input = JOptionPane.showInputDialog( chooseDir );
choice = Integer.parseInt( input );
When the user is playing through the maze and accidently hits enter or clicks OK with no input in the space, the program crashes. I beleive it's because it is trying to compare an integer and null value, but I can't figure out how to avoid it.
Can someone help me?
Thanks a million in advance :-)
Evil
|
|
|
import javax.swing.JOptionPane;
public class NullTest
{
public static void main(String[] args)
{
int value = -1;
boolean tryItAgain = true;
while(tryItAgain)
{
String retVal = JOptionPane.showInputDialog(null, "enter integer");
if(retVal == null || retVal.equals(""))
continue;
try
{
value = Integer.parseInt(retVal);
}
catch(NumberFormatException nfe)
{
continue;
}
tryItAgain = false;
}
JOptionPane.showMessageDialog(null, "you entered " + value);
}
}
|
|
|
|
|
Thanks crwood!
Works great, I never thought of comparing the string to null. You've been a great help :-)
Evil
|
|
|
|
|
|
|
// |