我试图设置一个要求只输入一个整数,如果输入任何其他内容显示错误消息

时间:2013-02-28 19:43:22

标签: java if-statement joptionpane

        ans = JOptionPane.showInputDialog(null,"There are currently "+clubSize+" people inside right now" +
                                                            "\nHow many People are in your party today.");
        int partyIn;
        try
            {
           partyIn = Integer.parseInt(ans);
            }
        catch (NumberFormatException e)
            {
           JOptionPane.showMessageDialog(null, "What you entered was not a number: " + ans);
            }
        if (clubSize + partyIn <= 125)
            {
            clubSize = clubSize + partyIn; 
            peopleIn = peopleIn + partyIn;
            }
        else
            {
            JOptionPane.showMessageDialog(null, "Sorry you have to many people in your party");
            }

这回来时出现错误:变量partyIn可能尚未初始化

1 个答案:

答案 0 :(得分:1)

如果输入的数字不是实数,Integer.parseInt将抛出NumberFormatException这一事实。捕获该异常,然后通知用户该错误。

int partyIn;
try
{
   partyIn = Integer.parseInt(ans);
}
catch (NumberFormatException e)
{
   JOptionPane.showMessageDialog(null, "What you entered was not a number: " + ans);
}