我收到此消息:
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
}
}
答案 0 :(得分:3)
我无法看到您宣布sinsertMoney
的位置,但看起来您已忘记将您的通话结果分配给JOptionPane.showInputDialog
,这就是为什么当您尝试解析它时,该值仍为null。
试试这个:
sinsertMoney = JOptionPane.showInputDialog(
"============================="
+ "\nPlease enter some money (in pence)"
+ "\n============================="); // Inserting money
insertMoney = Integer.parseInt(sinsertMoney);
答案 1 :(得分:1)
您需要在sinsertMoney
中输入输入值,如:
sinsertMoney = JOptionPane.showInputDialog(
"============================="
+ "\nPlease enter some money (in pence)"
+ "\n=============================");
并对{strong>取消操作和空字符串 sinsertMoney
执行空检查。