Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

}

}

like image 983
AppSensei Avatar asked Oct 02 '12 17:10

AppSensei


People also ask

How do you determine if an array is divisible by 3?

To solve this problem, we will check its divisibility by 3. Divisibility by 3 − a number is divisible by 3 if the sum of its digits is divisible by 3.

How do you check if a number is divisible by 3?

Add the digits of the number and check if this result is also divisible by 3. We add the individual digits of the number 7, 749, 984. 7 + 7 + 4 + 9 + 9 + 8 + 4 = 48.

How do you write divisible by 3 in Java?

var number = 21; if( number % 3 == 0) { //The number is divisible by three.

How do you check if a number is divisible by all elements of array?

Given an array of numbers, find the number among them such that all numbers are divisible by it. If not possible print -1. Examples: Input : arr = {25, 20, 5, 10, 100} Output : 5 Explanation : 5 is an array element which divides all numbers.


1 Answers

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.

like image 164
assylias Avatar answered Oct 14 '22 23:10

assylias