java数组

2016-11-07  本文已影响11人  Demons_96

数组的定义

test.java

//导入java.util包下的Scanner类
import java.util.Scanner;
public class test {
    public static void main(String[] args) {
        //定义数组[]可以放在数组明前也可以放在数组名后
        
        //动态初始化
        int []a;
        a=new int[2];
        a[0]=1;
        a[1]=2;
        //使用foreach遍历一维数组
        for(int x:a){
            System.out.print(x+" ");
        }
        
        //静态初始化
        int []b=new int []{1,2,3,4,5};
        for(int x:b){
            System.out.print(x+" ");
        }
        System.out.println();
        
        //二维数组静态初始化
        int [][]c={
            {1,2},
            {3,4},
            {5,6}
        };
        System.out.println("c的一维长度:"+c.length+","+"c的二维长度:"+c[0].length);
        //使用foreach遍历二维数组
        for(int[] x:c){
            for(int y:x){
                System.out.print(y+" ");    
            }
        }
        System.out.println();
        
        //输入对象
        Scanner scanner = new Scanner(System.in);
        //二维长度不等
        int[][]d=new int[2][];
        d[0]=new int[3];
        d[1]=new int[4];
        for(int i=0;i<d.length;i++){
            for(int j=0;j<d[i].length;j++){
                System.out.print("d["+i+"]"+"["+j+"]=");
                d[i][j]=scanner.nextInt();
            }
        }
        for(int[] x:d){
            for(int y:x){
                System.out.print(y+" ");    
            }
            System.out.println();
        }
        System.out.println();
    }
}
test.java执行结果

对象数组

类名[] 数组名 = new 类名[长度];

Student[] array = new Student[5];

也可以这样

Student[] array;
array = new Student[5];

然后实例化对象数组中的每个元素

array[0] = new Student("mmc","小六年4班",12);
array[1] = new Student("bh","初二年2班",14);
array[2] = new Student("xl","初三年2班",15);
array[3] = new Student("as","高二年5班",17);
array[4] = new Student("demon","大二年4班",20);

或者创建对象数组的同时实例化每个对象元素

Student[] array2 = new Student{
  new Student("w","初三年2班",15),
  new Student("l","高二年某班",17)
}

Student[] array2 = {
  new Student("w","初三年2班",15),
  new Student("l","高二年某班",17)
}

上一篇下一篇

猜你喜欢

热点阅读