input system where the user inputs the array position of the object followed by a # to indiacte quantity but it gives me an error
这是一个小卖部的计划!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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/
给出错误
Exception in thread"main" java.lang.NumberFormatException: For input string:"1#3"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
您将同一个字符串拆分两次,但字符串是不可变的,所以当原始字符串保持不变时,您将返回两个不同的数组。因此,如果您有如下输入:
1 | 1#3 2#4 |
你用
1 2 | 1#3 2#4 |
稍后在此行尝试将其解析为整数:
1 |
这将引发一个数字格式异常。您需要使用