这是一个小吃店计划!
public void sale() {
if (!ingredients.isEmpty()) {
printFood();
String choice = JOptionPane.showInputDialog("Enter Your choices seperatad by a # to indicate quantity");
String[] choices = choice.split(" ");
String[] ammounts = choice.split("#");
for (int i = 0; i < choices.length; i++) {
int foodPos = (Integer.parseInt(choices[i])) - 1;
int ammount = Integer.parseInt(ammounts[i+1]);
try {
foods.get(foodPos).sale(ammount);
} catch (IndexOutOfBoundsException e) {
System.out.println("Ingredient does not exsist");
}
}
}
}
http://paste.ubuntu.com/5967772/
给出了错误
线程“main”中的异常java.lang.NumberFormatException:对于输入字符串:java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)中的输入字符串:“1#3”,位于java.lang.Integer.parseInt(Integer.java: 492)在java.lang.Integer.parseInt(Integer.java:527)
1 回答
你将相同的字符串拆分两次,但是字符串是不可变的,所以当原始字符串保持不变时,你会得到两个不同的数组 . 因此,如果您输入如下:
你用
(" ")
拆分它将产生:您尝试稍后在此行解析为Integer:
这就是抛出NumberFormatException . 您需要使用
("#")
而不是源字符串重新拆分每个单独的数组元素 .