数组的元素类型和数组的大小都是确定的,所以当处理数组元素时候,我们通常使用基本循环或者foreach循环。
示例
该实例完整地展示了如何创建、初始化和操纵数组:
public class TestArray {
public static void main(String[] args) {
double [] myList = { 1.9 , 2.9 , 3.4 , 3.5 };
// 打印所有数组元素
for ( int i = 0 ; i < myList.length; i++) {
System.out.println(myList[i] + " " );
}
// 计算所有元素的总和
double total = 0 ;
for ( int i = 0 ; i < myList.length; i++) {
total += myList[i];
}
System.out.println( "Total is " + total);
// 查找最大元素
double max = myList[ 0 ];
for ( int i = 1 ; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println( "Max is " + max);
}
}
|
以上实例编译运行结果如下:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
2015职称计算机考试书PowerPoint2007中 .. 定价:¥45 优惠价:¥42 更多书籍 | |
2015年全国职称计算机考试教材(2007模 .. 定价:¥225 优惠价:¥213 更多书籍 |