为什么不尝试并抓住工作?

时间:2015-08-04 18:33:48

标签: java try-catch

我试图制作一个程序,告诉他们是否可以乘坐过山车。只要输入有效,它就可以工作,但我希望它显示一条消息,说明如果用户输入其他内容则重试。我尝试使用try和catch,但它仍然显示错误(NumberFormat异常)。感谢任何帮助。谢谢。

private void btnCalculateActionPerformed(java.awt.event.ActionEvent evt) {                                             
    String strHeight, strBackTrouble, strHeartTrouble;
    int intHeight;

    strHeight = txtInputHeight.getText();
    strBackTrouble = txtInputBackTrouble.getText();
    strHeartTrouble = txtInputHeartTrouble.getText();

    intHeight = Integer.parseInt(strHeight);

    try {
        if (intHeight < 188 || intHeight > 122) {
            if (strBackTrouble.equals("N") || strBackTrouble.equals("n") || strHeartTrouble.equals("N") || strHeartTrouble.equals("n")) {
                    txtOutput.setText("It is OK for you to ride this roller coaster. Have fun!");
            }
        } else  if (strBackTrouble.equals("Y") || strBackTrouble.equals("y") || strHeartTrouble.equals("Y") || strHeartTrouble.equals("y")) {
                txtOutput.setText("Sorry, it is not safe for you to ride this rollercoaster");
            }

    } catch (Exception e) {
        txtOutput.setText("You entered invalid input, please try again");
    }

}                 

2 个答案:

答案 0 :(得分:6)

intHeight = Integer.parseInt(strHeight); 

抛出不在catch块中的Exception。

答案 1 :(得分:0)

try {
    intHeight = Integer.parseInt(strHeight);
    if (intHeight < 188 || intHeight > 122) {
        if (strBackTrouble.equals("N") || strBackTrouble.equals("n") || strHeartTrouble.equals("N") || strHeartTrouble.equals("n")) {
                txtOutput.setText("It is OK for you to ride this roller coaster. Have fun!");
        }
    } else  if (strBackTrouble.equals("Y") || strBackTrouble.equals("y") || strHeartTrouble.equals("Y") || strHeartTrouble.equals("y")) {
            txtOutput.setText("Sorry, it is not safe for you to ride this rollercoaster");
        }

} 
catch(NumberFormatException e) {
    txtOutput.setText("You entered invalid number, please try again");
}
catch( Exception e) {
    txtOutput.setText("You entered invalid input, please try again");
}

java 7:

try {
    intHeight = Integer.parseInt(strHeight);
    if (intHeight < 188 || intHeight > 122) {
        if (strBackTrouble.equals("N") || strBackTrouble.equals("n") || strHeartTrouble.equals("N") || strHeartTrouble.equals("n")) {
                txtOutput.setText("It is OK for you to ride this roller coaster. Have fun!");
        }
    } else  if (strBackTrouble.equals("Y") || strBackTrouble.equals("y") || strHeartTrouble.equals("Y") || strHeartTrouble.equals("y")) {
            txtOutput.setText("Sorry, it is not safe for you to ride this rollercoaster");
        }

} catch (NumberFormatException e | Exception e) {
    txtOutput.setText("You entered invalid input, please try again");
}