This week's book giveaway is in the Java in General forum.
We're giving away four copies of Think Java: How to Think Like a Computer Scientist and have Allen B. Downey & Chris Mayfield on-line!
See this thread for details.
Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Need help with a For Loop

 
Nelly Verccety
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is my for loop:
for (int i=0; i< 10; i++) {
ArrayList row = (ArrayList) results.get(i);
Double amount_due = (Double) row.get(0);
Double amount_received = (Double) row.get(1);
System.out.println("Amount due = " + amount_due);
}

I don't get any error, what I want is a better way to end the loop. Because it says to end when it is less than 10. I want to end when the array actually ends. Because I know that there are 10 results, but I know there is a better way to end the loop. Like a method or something, a more professional way to end it, what if there are millions of values?

Thanks in advance...
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is "results" ? You should check for the size of this "results" variable.
 
Nelly Verccety
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh sorry, results is of type ArrayList.

So it is declared like this:

ArrayList results = DataAccess.executeQuery(theDBConnection, table,
fields, on, where, groupBy, orderBy);
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int end = results.size();
for (int i=0; i<end; ++i)
   ...
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So you could do :
for (int i=0; i< results.size(); i++)

This will loop until the end of the array.
 
Nelly Verccety
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sweet, I love you man.

Thanks ^^
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic