JavaSE 基础 第19节 如何使用数组

2016-06-29

1 获取数组长度

int[] array1=new int[10];
System.out.println(array1.length);

package com.java1995;

import java.util.Scanner;

public class Test {
    
    public static void main(String[] args) {
//        int[] array1=new int[10];
//        System.out.println(array1.length);
        
        //学生成绩管理系统
        int student;//控制学生的变量
        double sum=0,avg=0;//总成绩和平均成绩
        double[] temp=new double[10];
        //创建一个Scanner类的对象,用它来获得用户的输入
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入10名学生的成绩");
        
        for(student=0;student<temp.length;student++){
            //读取用户的输入
            temp[student]=sc.nextDouble();
            sum+=temp[student];
        }
        
        avg=sum/10;
        
        System.out.println("平均值是:"+avg);
        
        for(student=0;student<temp.length;student++){
            
            if(temp[student]<avg){
                System.out.println("该学生的成绩为:"+temp[student]+",低于平均成绩:"+avg);
            }else if(temp[student]==avg){
                System.out.println("该学生的成绩为:"+temp[student]+",等于平均成绩:"+avg);
            }else{
                System.out.println("该学生的成绩为:"+temp[student]+",高于平均成绩:"+avg);
            }
        }
        
    }

}

2 数组的复制
array1=array2;
复制之后,两个引用指向同一个数组,不管是哪一个引用修改了数组元素的值,
对另一个引用来说,元素的值也是修改过的。

package com.java1995;

public class Test2 {
    
    public static void main(String[] args) {
        int[] array1={1,2,3};
        int[] array2={4,5,6};
        
        System.out.println("两个数组的初始值为:");
        for(int i=0;i<array1.length;i++){
            System.out.println("array1["+i+"]="+array1[i]);
        }
        
        for(int i=0;i<array2.length;i++){
            System.out.println("array2["+i+"]="+array2[i]);
        }
        
        //把array2赋值给array1
        array1=array2;
        System.out.println("array2赋值给array1后:");
        for(int i=0;i<array1.length;i++){
            System.out.println("array1["+i+"]="+array1[i]);
        }
        
        for(int i=0;i<array2.length;i++){
            System.out.println("array2["+i+"]="+array2[i]);
        }
        
        //给array1重新赋值
        array1[0]=100;
        array1[1]=300;
        array1[2]=98;
        System.out.println("arr1重新赋值后:");
        for(int i=0;i<array1.length;i++){
            System.out.println("array1["+i+"]="+array1[i]);
        }
        
        for(int i=0;i<array2.length;i++){
            System.out.println("array2["+i+"]="+array2[i]);
        }
    }

}

【参考资料】

[1] Java轻松入门经典教程【完整版】

原文地址:https://www.cnblogs.com/cenliang/p/5626941.html