-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());
    }
}

我如何断言用户将输入一个数字(非零)?是否可以使用 OR 运算符 (||) 将其添加到 if 语句中?

4

1 回答 1

1

我会在解析 int 的行周围添加一个 try-catch 块,并让它捕获一个 NumberFormatException。这样,如果用户没有输入具有“可解析整数”的字符串,您的程序就不会崩溃。您可以将 JOptionPane 消息放在 catch 块中。这也将捕获字符串长度为 0 的情况,因此您可能不需要该 if 语句。您可以使用 if 语句轻松测试该数字是否不为零。

这是我将如何编码。

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)

于 2013-06-09T01:50:38.173 回答