Java Basic - explanation of for loops
Code Java:
class GraphPanel extends Panel
//GraphPanel is being defined as subclass of Panel
implements Runnable, MouseListener, MouseMotionListener { //runnable
//using an interface, allows q method from ore than one superclass
Graph graph; //attribute or variable
int nnodes; //attribute or variable, primitive data type
Node nodes[] = new Node[100];
int nedges; //attribute or variable intial value
Edge edges[] = new Edge[200];
Thread relaxer;
GraphPanel(Graph graph) {
this.graph = graph;
addMouseListener(this);
}
int findNode(String lbl) {
for (int i = 0 ; i < nnodes ; i++) {
//statement executes if test returns true
}
}
Just in regards to the for loop, not sure what the i < nnodes is testing. Is it comparing i to the individual value of each nnodes variable, or is it comparing to see whether i is less than the length of nnodes array?
Re: Java Basic - explanation of for loops
nnodes is an integer variable. It's comparing i to the integer value of nnodes.
Re: Java Basic - explanation of for loops
The "for" statement does 3 things. First you declare/intantiate something. Then you declare a condition. Finally, you declare an action. In your example, you create an integer 'i', check that the value of 'i' is less than the value of 'nnodes', and if so, add 1 to the value of 'i'. The loop is repeated as long as these conditions are met.
Code :
for(int i=0; i< nnodes; i++)
{
//Put code here that you want to be executed every time the conditions of the loop are met.
}