例子3.3 声明一个整型数组并对他初始化,在屏幕上输出各元素的值与其总和。
1 public class IntArray 2 { 3 public static void main (String args []) 4 { 5 int a [] = {1,2,6}; 6 int i, sum = 0; 7 for (i = 0; i < a.length; i++) 8 sum = sum + a[i]; 9 for (i = 0; i <a.length; i++) 10 System.out.println("a ["+ i +"] = " + a[i]); 11 System.out.println("sum= "+ sum); 12 } 13 }
例子3.4 求一维数组的长度,并输出结果
1 public class ArrayLength 2 { 3 public static void main (String [] args ) 4 { 5 int a [] = {1,2,3,4,9}; 6 System.out.println ("length:" + a.length + "\n"); 7 for (int i = 0; i< a.length; i++) 8 System.out.print (a [i]+ " "); 9 a = new int [8]; 10 System.out.println (); 11 System.out.println ("length:" + a.length + "\n"); 12 a [0] = 1; 13 a [1] = 10; 14 for (int i = 0; i < a.length; i++) 15 System.out.print(a [i] + " "+ "\n"); 16 } 17 } 18