苹者演大孝 South China Agr icultur al Uni versity ■数组声明和初始化方法: scores 79 87 int[l scores new int[101 scores 94 ■或 int scores[]= mew int[10]; 82 ■或int[] scores= 67 98 79,87,94,82,67,9887,81,74,91}; 87 使用初始值表就不需要用new运算符。 81 ■上面的语句执行结果如图1: 74 ■如果继续对数组 scores初始化: 91 结果如图2: 图2 图1
6 ◼ 数组声明和初始化方法: ◼ int[] scores = new int[10]; ◼ 或 int scores[] = new int[10]; ◼ 或 int[] scores = {79,87,94,82,67,98,87,81,74,91}; 使用初始值表就不需要用new运算符。 ◼ 上面的语句执行结果如图1: ◼ 如果继续对数组scores初始化: 结果如图2: scores scores 79 87 94 82 67 98 87 81 74 91 图1 图2
■声明数组 scores: sc。es 79 ■数组变量的类型(int)中 87 没有指定数组的大小 94 82 用new运算符实例化数组 67 98 后,预留了存放10个整型的 87 内存空间,索引好是0到9。 81 74 ■一且将数组声明为确定的 91 大小后,该数组能够保存的 值的个数就不可以再改变。 数组 scores声明: int[] scores= new int[10
◼ 声明数组 scores : scores 79 87 94 82 67 98 87 81 74 91 数组scores声明 : int[ ] scores = new int[10]; ◼ 数组变量的类型(int[ ])中 没有指定数组的大小。 ◼ 用new运算符实例化数组 后,预留了存放10个整型的 内存空间,索引好是0到9。 ◼ 一旦将数组声明为确定的 大小后,该数组能够保存的 值的个数就不可以再改变
声明数组 float prices new float [500 用于指定数组索引的 ■boo|ean[]fags; 方括号在java中解释 为运算符,在java所 有的运算符中,索引 ■fags= new boolean[20]},预算符“[y”有最高 的优先级。 char[ codes= new char[ 1750
◼float[ ] prices = new float [500]; ◼boolean[ ] flags; ◼ flags = new boolean[20]; ◼ char[ ] codes = new char[1750]; 声明数组 用于指定数组索引的 方括号在java中解释 为运算符,在java所 有的运算符中,索引 预算符 “[ ]”有最高 的优先级
苹者演大孝 South China Agr icultur al Uni versity 在处理数组元素的时候,可以使用 oreach语句来处理。 for (int score scores) System. out, println( score);Java数组都是迭代器 能够使用for循环的迭代 等价于: 器版提取指定迭代器中的 int score; 每个值。 while(scores. hasnext() 该循环适用在处理数组 score= scores. next(; 所有元素的情形,并且处 system. out. printin(score) 理的顺序是从索引值的最 小值到最大值 例题71 BasicArray. java (P243
◼ 在处理数组元素的时候,可以使用foreach语句来处理。 for (int score : scores) System.out.println (score); 等价于: int score; while(scores.hasnext()) { score= scores.next() ; system.out.println(score); } 该循环适用在处理数组 所有元素的情形,并且处 理的顺序是从索引值的最 小值到最大值。 例题7.1 BasicArray.java (P243) Java数组都是迭代器 能够使用for循环的迭代 器版提取指定迭代器中的 每个值
721边界检查 旦数组被创建,它的大小就固定了 ■寮引预算符会自动执行边界检查,可以保证只引用 数组有效范围内的索引置。 当访问一个数组的元素的时候,索引值必须大于等于 0并且小于等于数组的大小,否则将抛出异常 ArrayIndexOutofBoundsException ■数组的这一操作叫做自动边界检查。 例如:int[]= new int[100] problem for (int index=0; index <=(100 index++) codes [index] index*50 epsilon
◼ 一旦数组被创建,它的大小就固定了。 ◼ 索引预算符会自动执行边界检查,可以保证只引用 数组有效范围内的索引置。 ◼ 当访问一个数组的元素的时候,索引值必须大于等于 0 并且小于等于数组的大小,否则将抛出异常 ArrayIndexOutOfBoundsException. ◼ 数组的这一操作叫做自动边界检查。 7.2.1 边界检查 例如: int [ ] = new int [ 100] for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon; problem