Reputation: 8400
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
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
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
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
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:
Division
=> division
.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