尝试catch with contains for和if语句Java [关闭]

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了尝试catch with contains for和if语句Java [关闭]相关的知识,希望对你有一定的参考价值。

我的程序有问题。用户可以在GUI中输入成绩,但成绩必须在9到12年级。 这是我到目前为止所尝试的,但似乎没有用。

int grade = Integer.parseInt(inputGrade.getText());
else
    {
        try
        {
            for (int i = 9; i < 13; i++)
            {
                if (grade == i)
                {
                grade = Integer.parseInt(inputGrade.getText());
                }
            } 
        }

        catch(NumberFormatException e)
        {            
            for (int x = -1; x < 9; x++)
            {
                if (grade == x)
                {
                outputHint.setText("Grade not valid");
                }
            }
        }

没有提示输出。

有什么帮助吗?提前致谢!!

答案

你尝试过这样的事吗?

try
{
    grade = Integer.parseInt(inputGrade.getText());
    if (grade >= 9 && grade <= 12) {
        // Valid
        outputHint.setText("Grade valid");
    } else {
        // Not valid
        outputHint.setText("Grade not valid");
    }
}
catch(NumberFormatException e)
{
    outputHint.setText("Grade not valid");
}

你还有在比较它之前比较grade变量的问题。并且你的for循环没有用,因为一旦它是一个整数你就可以对你的变量做一个条件。

最后,只有当throw是非整数时,你的例外才是inputGrade.getText()。所以它没有考虑你的if条件,所以你甚至不能在那之后把坏数字放在那里。

另一答案

这是一个简单的方法。

    try{

        int grade = Integer.parseInt(inputGrade.getText());
        if(grade >= 9 && grade <= 12){
          // this is a good grade
           outputHint.setText("Grade valid");
        } else {
         // sorry, this is not a good grade.
         outputHint.setText("Grade not valid");
        }
        } catch(NumberFormatException e) {
         // sorry but you need to enter a number !!
        }
另一答案
    try  {
        int grade = Integer.parseInt(inputGrade.getText());
        if (grade < 9 || grade > 12) {
            outputHint.setText("Grade not valid");
        }
    } catch(NumberFormatException e) {
        outputHint.setText("Grade not valid");
    }
另一答案

仅当输入的输入无法转换为NumberFormatException时,捕获Integer才会出现异常。也许你也错过了最初的if

以上是关于尝试catch with contains for和if语句Java [关闭]的主要内容,如果未能解决你的问题,请参考以下文章