-2
for (int i = 0; i < fields.length; i++)
{
    for (int j = 0; j < fields[i].length; j++)
    {
        if (fields[i][j].getText().length() == 0) //IF ZERO OR NOT A NUMBER
        {
            JOptionPane.showMessageDialog(null, "Answers missing");
            return;
        }
        answers[i][j] = Integer.parseInt(fields[i][j].getText());
    }
}

How can I assert that a user will input a number (other than zero)? Is it possible to just add it to the if statement using an OR operator (||)?

0

1 Answer 1

1

I would add a try-catch block around the line where you parse the int, and have it catch a NumberFormatException. That way, if the user does not input a string that has a "parsable integer", your program won't crash. You could probably put the JOptionPane message in the catch block. This will also catch a situation where the length of the string is 0 so you probably don't need that if statement. You can easily test to see if the number is not zero with an if statement.

Here's how I would code it.

for (int i = 0; i < fields.length; i++)
{
    for (int j = 0; j < fields[i].length; j++)
    {

        try {
            int probableAnswer = Integer.parseInt(fields[i][j].getText());

            if(probableAnswer == 0) {
             JOptionPane.showMessageDialog(null, "Answers missing");
            }
            else {
                answers[i][j] = probableAnswer;
            }

        } //end try block
        catch(NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "Answers missing");
        }
    }
}

http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#parseInt(java.lang.String)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.