package shenhui; public class code11{ public static void main(String[] args){ double bookprice[]=new double [10]; double bookpricebak[]=bookprice; //数组的赋值,只是将bookprice数组的内存地址给了bookpricebak,实际上只有一个数组实例 double copybookprice[]=new double[bookprice.length]; double halfbookprice[]=new double[bookprice.length]; System.out.print("(for循环输出)每本书的价格是"); for(int a=0;a<bookprice.length;a++){ //bookprice.length为数组bookprice的长度 //使用for循环给bookprice中每个元素赋值,也可以使用bookprice[0]=100;这样给每个元素赋值 //或者int bookprice[]={100,101,102……};数组长度由{}个数决定 bookprice[a]=100+a; //注意此处的a是索引值,索引从0开始 System.out.print(bookprice[a]+" "); //在for循环中打印出每个元素 } System.out.println(); System.out.print("(for-each输出)每本书的价格是"); for(double price:bookprice){ //使用for-each取出数组中的每个元素,for-each不需要像传统for循环般设定初始值、条件式和变量 //for-each循环会自动将数组中元素由第一个依次取到最后一个 //此处的price代表的是元素值 System.out.print(price+" "); } System.out.println(); System.out.print("bookpricebak数组内容:"); for(double i:bookpricebak){ System.out.print(i+" "); } System.out.println(); System.arraycopy(bookprice,0,copybookprice,0,bookprice.length/2); //用arraycopy方法完成数组的复制,bookprice与copybookprice有单独的内存地址 System.out.print("copybookprice数组内容"); for(double i:copybookprice){ System.out.print(i+" "); } System.out.println(); System.out.print("将bookprice打半价"); for(int i=0;i<bookprice.length;i++){ halfbookprice[i]=bookprice[i]*0.5; System.out.print(halfbookprice[i]+" "); } } }
输出结果:
(for循环输出)每本书的价格是100.0 101.0 102.0 103.0 104.0 105.0 106.0 107.0 108.0 109.0
(for-each输出)每本书的价格是100.0 101.0 102.0 103.0 104.0 105.0 106.0 107.0 108.0 109.0
bookpricebak数组内容:100.0 101.0 102.0 103.0 104.0 105.0 106.0 107.0 108.0 109.0
copybookprice数组内容100.0 101.0 102.0 103.0 104.0 0.0 0.0 0.0 0.0 0.0
将bookprice打半价50.0 50.5 51.0 51.5 52.0 52.5 53.0 53.5 54.0 54.5