5

因为我正在探索 ArrayLists,所以我这样做纯粹是为了好玩。我知道如何使用模运算符来检查它是否可以被 3 整除。但是,知道如何将它与 arrayList 一起使用。

public static void main(String[] args) {

    //Print out only a set of numbers divisible by 3 from an array.

    ArrayList<Integer> division = new ArrayList<Integer>();

    //Add a set of numbers.
    Division.add(10);
    Division.add(3);
    Division.add(34);
    Division.add(36);
    Division.add(435);
    Division.add(457);
    Division.add(223);
    Division.add(45);
    Division.add(4353);
    Division.add(99);


    //How can I fix the logic below?
    if(Division.get() % 3 == 0)

}

}

4

4 回答 4

6

您需要遍历列表中的项目,例如,使用增强的 for 循环语法:

for (int i : Division) {
    if (i % 3 == 0) {
        System.out.println(i + " is divisible by 3");
    }
}

笔记:

  • 您应该应用 java 命名约定。特别是,变量名以小写开头(常量除外):Division=> division
  • 你的division对象实际上是一个数字列表,所以numbers可能是一个更好的名字。

有关Java 教程中的列表的更多信息。

于 2012-10-02T17:08:45.313 回答
6
for(Integer number: division){
  if(number % 3 == 0){
    System.out.println(number);
  }
}

作为 Java 命名约定:只有类以大写字母开头。变量以小写字母开头,所以这样更好:ArrayList<Integer> division = new ArrayList<Integer>();

于 2012-10-02T17:09:33.490 回答
5

或者,您也可以使用“正常” for 循环:

for (int i = 0; i < Division.size(); i++)
     {
       if(Division.get(i) % 3 == 0)
       {
        System.out.println(Division.get(i));
       }
     }
于 2012-10-02T17:14:58.200 回答
3

First of all, you should declare your variable starting with lowercase alphabet or underscore..

Second you need to iterate over your ArrayList to fetch it's element, and your ArrayList should be of Wrapper Type Integer not of Primitive type int..

ArrayList<Integer> division = new ArrayList<Integer>();
// Initialize your arraylist here
for (Integer i : division) {
    if (i % 3 == 0) {
        System.out.println("Number : " + i + "is divisible by 3");
    }
}

Take a look at this blog.. It has wide examples covering how to iterate over List..

于 2012-10-02T17:11:24.847 回答