【问题标题】:Can not add elements to ArrayList<Integer>无法将元素添加到 ArrayList<Integer>
【发布时间】:2019-05-12 04:07:55
【问题描述】:

所以我试图创建一个整数数组列表,然后将变量迭代到其中。仅添加我指定的第一个值。

 private ArrayList<Integer> heights(String detail) {
        ArrayList<Integer> heights = new ArrayList<Integer>();
        heights.add(0);
        switch(detail) {
            case "L": for(Integer i = 100; i <= 1000; i=+50) { heights.add(i); } break;
            case "H": for(Integer i = 100; i <= 1000; i=+25) { heights.add(i); } break;
        }
        return heights;
    }

高度值(“H”):

高度:[0]

【问题讨论】:

  • detail 的值是多少?如果既不是 L 也不是 H 则没有其他内容可添加到列表中

标签: java arraylist integer


【解决方案1】:

问题出在 for 循环中。 使用int 而不是Integer 类....

下面的代码可以正常工作...

import java.util.*;  
class Test{
        private ArrayList<Integer> heights(String detail) {
            ArrayList<Integer> heights = new ArrayList<Integer>();
            heights.add(0);
            switch(detail) {
                case "L": for(int i = 100; i <= 1000; i=i+50) { heights.add(i); } break;
                case "H": for(int i = 100; i <= 1000; i=i+25) { heights.add(i); } break;
            }
            return heights;
        }
     public static void main(String args[]){
            Test t = new Test();
            System.out.println(t.heights("H"));
         }
    } 

【讨论】:

  • @GhostCat 已更新答案,感谢您的指正
  • 您可能想解释一下为什么会这样,但肯定比以前更好。
  • 编辑这个来解释你提到的问题。
猜你喜欢
  • 2012-01-03
  • 2021-03-19
  • 2015-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-11
相关资源
最近更新 更多