如何使用Scanner将元素添加到ArrayList中

时间:2017-01-21 04:16:59

标签: java arraylist

所以我的问题是我想使用Scanner kb将元素添加到ArrayList中。我还想确保输入(数字)介于0和100之间(包括0和100)。我的代码没有按我的意愿运行。我该如何解决这个问题?感谢。

JSON.stringify()

2 个答案:

答案 0 :(得分:2)

  1. 更改您的陈述

    for(int x = 0; x < myAList.size() - 1; x++); 
    // the semicolon terminates loop without any action block
    // myAList.size() would keep on increaing with every `add()` inside the loop.
    

    int listSize = myAList.size();
    for(int x = 0; x < listSize - 1; x++) {
        myAList.add(number);
    }
    
  2. 代码中不需要语句kb.nextLine();nextDouble()负责接受退货并转到控制台的下一行。

  3. 与(1)相反,如果您只想添加输入到现有列表的数字,则无论如何都不需要for循环。只需在while循环之后,执行

    myAList.add(number);
    
  4. 请注意,如果myAListnull,则您的语句myAList.trimToSize();可能会抛出NPE。因为它在if块之外进行空检查。将其移到if里面就是我的建议。

  5. 这应该可以正常工作 -

    public static void addNum(final ArrayList<Double> myAList, final Scanner kb) {
        if (!(kb == null || myAList == null)) {
            System.out.println("Please enter a number between (0 - 100): ");
            double number = kb.nextDouble();
            while (number < 0d || number > 100d) {
                System.out.println("That was not a qualified number, try again");
                number = kb.nextDouble();
            }
            myAList.add(number);
            myAList.trimToSize();
            System.out.println(Arrays.asList(myAList.toArray()));
        }
    }
    

答案 1 :(得分:1)

如果您使用final关键字,请确保您没有选择死胡同。您的代码if(!(kb == null || myAList == null))中存在小错误,如果其中任何一个null失败,则可能会失败,因此请确保您正确检查,以下是有效的示例

public void addNum(final List<Double> myAList, final Scanner kb) {
        double number;
        if (!(myAList == null && kb == null)) {
            System.out.println("Please enter a number between (0 - 100): ");
            number = kb.nextDouble();
            while (number < 0d || number > 100d) {
                System.out.println("please enter double and number must be betwen  0 to 100");
                number = kb.nextDouble();
            }
            myAList.add(number);
            System.out.println(myAList);
        }
    }