Ethan
Ethan

Reputation: 83

This for loop defines a condition but later ignores it

/If the for loop goes to i< numbers.length then how would it ever end up at i == numbers.length? Wouldn't it stop iterating at numbers.length-1?/

class Phone {
    public static void main(String args[]){
      String numbers[][] = {
        {"Tom", "535-5334"},
        {"Bill", "432-5432"}
      };

      int i;

      if(args.length != 1)
        System.out.println("Usage: java Phone <name>");
      else {
        for(i=0; i<numbers.length; i++) {
          if(numbers[i][0].equals(args[0])){
           System.out.println(numbers [i] [0] + ":" + numbers [i][1]);
           break;
          }
        }
      if(i == numbers.length)
        System.out.println("name not found");
      }
    }
}

This example is in my introductory java book and I don't understand it. It would make sense to me if the for loop used i<=numbers.length

Upvotes: 0

Views: 55

Answers (1)

lebolo
lebolo

Reputation: 2150

From the docs,

for (initialization; termination; increment) {
 statement(s)
}

...The increment expression is invoked after each iteration through the loop...

So if a name is not found in the numbers array, the for loop counter i goes up to numbers.length, the termination numbers.length < numbers.length fails and the for loop exits.

Therefore, i = numbers.length at the exit of the loop and the message is printed.

On the other hand, if a name is found within the array, then the for loop breaks out before i reaches numbers.length and the message is not printed.

Upvotes: 1

Related Questions