gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:48:27 25 4
gpt4 key购买 nike

        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 可能尚未初始化

最佳答案

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

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

关于java - 我试图设置一个要求,只输入一个整数,如果输入其他任何内容,则显示错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15144258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com