gpt4 book ai didi

java.lang.NumberFormatException - 找不到错误所在

转载 作者:行者123 更新时间:2023-12-01 18:31:49 25 4
gpt4 key购买 nike

我收到此消息:

Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:454)
at java.lang.Integer.parseInt(Integer.java:527)
at fdc.programming.VendingMachine.InsertMoney(VendingMachine.java:70)
at fdc.programming.VendingMachineDriver.main(VendingMachineDriver.java:30)
Java Result: 1

我一直在尝试解决如何进行验证循环,以便只接受正整数,但我暂时放弃了,但我没有更改任何内容,并将所有内容恢复为乱七八糟之前的样子。现在,当我尝试输入数字时,它会出现上述错误,但 Netbeans 中没有错误,我可以用它来找出问题所在!请注意,我在大学只完成了一个 Java 基本模块;)

我的代码是:

public class VendingMachine
{
String sinsertMoney, sinsertMoney2; // Money inserted value for parsing into int
String productName; // Name of product

int insertMoney, insertMoney2; // Money inserted by customer (int = pence)
int price; // Price of products on sale
int changeLeft; // Change left from inserted money after selection

int again; // variable for deciding program repeat

DecimalFormat pence = new DecimalFormat("#p"); // Format display output for pence

public void InsertMoney() {
String soption; // Variable for machine operation
productName = " Nothing";
insertMoney = 0; // Default inserted money initialised to zero
insertMoney2 = 0; // Default additional inserted money initialised to zero
price = 0; // Initialising money variables

// Vending machine welcome dialog

soption = JOptionPane.showInputDialog(
"============================================"
+ "\nWelcome to the College Vending Machine!"
+ "\n============================================"
+ "\n\nOptions: i for insert money, s for select item, q for quit."
+ "\n\n============================================");

if ("q".equals(soption)) { // If user chooses q: quit
JOptionPane.showMessageDialog(null, "Have a Nice Day!");
System.exit(0); // terminate application
}
if ("i".equals(soption)) { // if user chooses i: insert money
JOptionPane.showInputDialog(
"============================="
+ "\nPlease enter some money (in pence)"
+ "\n============================="); // Inserting money
insertMoney = Integer.parseInt(sinsertMoney); // Parsing for calculations
}
if ("s".equals(soption)) { // if user chooses s: select item
}
}

最佳答案

我看不到您在何处声明了 sinsertMoney,但您似乎忘记将调用 JOptionPane.showInputDialog 的结果分配给某些内容,因此,当您尝试解析该值时,该值仍然为空。

试试这个:

sinsertMoney = JOptionPane.showInputDialog(
"============================="
+ "\nPlease enter some money (in pence)"
+ "\n============================="); // Inserting money
insertMoney = Integer.parseInt(sinsertMoney);

关于java.lang.NumberFormatException - 找不到错误所在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23853320/

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