繁体   English   中英

如何使用扫描仪将元素添加到ArrayList中

[英]How can I add elements into ArrayList using Scanner

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

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

        for(int x = 0; x < myAList.size() - 1; x++);
        {
            myAList.add(number);
        }
    }   
    myAList.trimToSize();
}
  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我建议的if将其移入内部。


这应该很好-

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()));
    }
}

如果您使用的是final关键字,请确保您没有选择“死胡同”。 if(!(kb == null || myAList == null))您的代码中if(!(kb == null || myAList == null))任何一个为nullif(!(kb == null || myAList == 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);
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM