AppSensei
AppSensei

Reputation: 8400

Find numbers divisible by 3 in an ArrayList

I am doing this for pure fun since I'm exploring into ArrayLists. I know how to use the modulus operator to check if it's divisible by 3. But, have know clue on how to use it with an 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)

}

}

Upvotes: 5

Views: 9640

Answers (4)

Simulant
Simulant

Reputation: 20112

for(Integer number: division){
  if(number % 3 == 0){
    System.out.println(number);
  }
}

As a Java naming convention: Only classes start with an upper case. Variables start with a lower case, so this is better: ArrayList<Integer> division = new ArrayList<Integer>();

Upvotes: 6

Thousand
Thousand

Reputation: 6638

alternatively, you can also use a "normal" for loop:

for (int i = 0; i < Division.size(); i++)
     {
       if(Division.get(i) % 3 == 0)
       {
        System.out.println(Division.get(i));
       }
     }

Upvotes: 5

Rohit Jain
Rohit Jain

Reputation: 213271

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..

Upvotes: 3

assylias
assylias

Reputation: 328629

You need to loop over the items in your list, for example, using the enhanced for loop syntax:

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

Note:

  • You should apply the java naming conventions. In particular, variable names start in lower case (apart from constants): Division => division.
  • And your division object is really a list of numbers, so numbers would probably be a better name.

More info about lists in the Java Tutorial.

Upvotes: 6

Related Questions