首页 文章

输入系统,用户输入对象的数组位置,后跟#到indiacte数量,但它给我一个错误

提问于
浏览
0

这是一个小吃店计划!

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 回答

  • 2

    你将相同的字符串拆分两次,但是字符串是不可变的,所以当原始字符串保持不变时,你会得到两个不同的数组 . 因此,如果您输入如下:

    1#3 2#4
    

    你用 (" ") 拆分它将产生:

    1#3
    2#4
    

    您尝试稍后在此行解析为Integer:

    int foodPos = (Integer.parseInt(choices[i])) - 1;
    

    这就是抛出NumberFormatException . 您需要使用 ("#") 而不是源字符串重新拆分每个单独的数组元素 .

相关问题