gpt4 book ai didi

java - 为什么我仍然收到 NumberFormatException 错误?

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

好吧,我很确定我已经处理了这个错误,但是每当我尝试测试一个字符串代替整数时,它都会不断发送错误,尽管我指定了处理它。

我使文本字段只接受整数,但是我希望它显示,如果输入字符串,它将发送一个 JOptionPane 说只允许数字。

这是我的整个代码:

    public void giveItem() {
try {
String itemId = textField1.getText();
String itemAmount = textField2.getText();

if (isTargetEmpty()){
JOptionPane.showMessageDialog(
null, "Please enter a player to continue!", "Error", JOptionPane.INFORMATION_MESSAGE
);
} else if (itemId.isEmpty() || itemAmount.isEmpty()){
JOptionPane.showMessageDialog(
null,"Please fill the required fields!", "Error",JOptionPane.INFORMATION_MESSAGE
);
} else {

String player = getTargetName();
Player target = World.getPlayerByDisplayName(player);
if (target != null) {

int id = Integer.parseInt(itemId);
int amount = Integer.parseInt(itemAmount);

if (Double.isNaN(id) || Double.isNaN(amount)){
JOptionPane.showMessageDialog(
null, "You can only enter numbers!", "Error!", JOptionPane.INFORMATION_MESSAGE
);

} else if (amount <= target.getInventory().getFreeSlots()) {

target.getInventory().addItem(id, amount);
target.getPackets().sendGameMessage(
"You have received " + (amount > 1 ? " Items!" : "an Item!")
);
JOptionPane.showMessageDialog(
null, Utils.formatPlayerNameForDisplay(target.getUsername()) + " has received the " +
(amount > 1 ? "Items successfully in his/her inventory." : "Item successfully in his/her inventory.")
);
logAction(SPSutil.getTime() + Utils.formatPlayerNameForDisplay(target.getUsername())
+ " has received the item : " + id + ". Amount : " + amount + " in his/her inventory."
);
} else {
target.getBank().addItem(id, amount, true);
target.getPackets().sendGameMessage(
"You have received " + (amount > 1 ? "Items in your bank!" : "an Item in your bank!")
);
JOptionPane.showMessageDialog(
null, Utils.formatPlayerNameForDisplay(target.getUsername()) + " has received the " +
(amount > 1 ? "Items successfully in his/her bank." : "Item successfully in his/her bank.")
);
logAction(SPSutil.getTime() + Utils.formatPlayerNameForDisplay(target.getUsername())
+ " has received the item : " + id + ". Amount : " + amount + " in his/her bank."
);
}
} else {
JOptionPane.showMessageDialog(
null , "Player does not exist!", "Error" , JOptionPane.INFORMATION_MESSAGE
);
}
}
} catch(IOException e){
e.printStackTrace();
}
}

最佳答案

Double.isNaN()解析后将不会检查数字是否有效。此方法的参数是一个 double(因此您的 id 会自动提升),并且它仅检查此 double 是否为 Double.NaNint 永远无法做到这一点,甚至无法提升。

你必须做的是:

try {
int id = Integer.parseInt(itemId);
} catch (NumberFormatException e) {
// not an integer
}

关于java - 为什么我仍然收到 NumberFormatException 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22630921/

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