0

/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

4

1 回答 1

1

文档中,

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

...在循环的每次迭代后调用增量表达式...

numbers因此,如果在数组中找不到名称,for 循环计数器i会上升到numbers.length,终止numbers.length < numbers.length失败并且 for 循环退出。

因此,i = numbers.length在循环的出口处打印消息。

另一方面,如果在数组中找到一个名称,则 for 循环breaki到达之前退出numbers.length并且不打印消息。

于 2013-09-08T00:10:39.707 回答