This is my code for printing the random numbers in an arraylist:
public void printList()
{
System.out.println("The numbers on the list: ") ;
for (int i = 0 ; i < aList.size() ; i++)
{
System.out.print( aList.get(i) + " ") ;
}
System.out.println("\n") ;
}
How would I print every other number of this same list? By using a do-while loop?
Put additional if statement inside your for block which would check for parity: if (i % 2 == 0) { System.out.print(... }
Above approach is ineffecient. Just increment the index by 2
public void print()
{
System.out.println("The numbers on the list: ") ;
for (int i = 0 ; i < aList.size() ; i+=2)
{
System.out.print( aList.get(i) + " ") ;
}
System.out.println();
}
public void print() {
System.out.println("The numbers on the list: ") ;
int i = 0;
for (Object o : aList) {
if (i % 2 == 0) {
System.out.print( o + " ") ;
}
i++;
}
System.out.println();
- ahanin 2012-04-04 20:01
Edit: This will cause an outOfBoundsException if aList.size() is odd.
Not on my Java! Can you write me an example - Ishtar 2012-04-04 21:00