java數(shù)組

數(shù)組的定義

test.java

//導(dǎo)入java.util包下的Scanner類
import java.util.Scanner;
public class test {
    public static void main(String[] args) {
        //定義數(shù)組[]可以放在數(shù)組明前也可以放在數(shù)組名后
        
        //動態(tài)初始化
        int []a;
        a=new int[2];
        a[0]=1;
        a[1]=2;
        //使用foreach遍歷一維數(shù)組
        for(int x:a){
            System.out.print(x+" ");
        }
        
        //靜態(tài)初始化
        int []b=new int []{1,2,3,4,5};
        for(int x:b){
            System.out.print(x+" ");
        }
        System.out.println();
        
        //二維數(shù)組靜態(tài)初始化
        int [][]c={
            {1,2},
            {3,4},
            {5,6}
        };
        System.out.println("c的一維長度:"+c.length+","+"c的二維長度:"+c[0].length);
        //使用foreach遍歷二維數(shù)組
        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執(zhí)行結(jié)果

對象數(shù)組

  • 語法

類名[] 數(shù)組名 = new 類名[長度];

  • 示例

Student[] array = new Student[5];

也可以這樣

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

然后實例化對象數(shù)組中的每個元素

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);

或者創(chuàng)建對象數(shù)組的同時實例化每個對象元素

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

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 如何學(xué)習(xí)一個知識點 首先了解知識點是什么第二為什么要用這個知識點然后如何用這個知識點 數(shù)組是什么 數(shù)組本身是個抽象...
    IsCoding閱讀 493評論 0 0
  • Java數(shù)組 數(shù)組無論在哪種編程語言中都算是最重要的數(shù)據(jù)結(jié)構(gòu)之一,同時不同語言的實現(xiàn)及處理也不盡相同。但凡寫過一些...
    java部落閱讀 433評論 0 1
  • 數(shù)組不管在任何一門語言中都有重要的位置,必會。第一部分,語法。 定義一個數(shù)組:int[] array = new ...
    轉(zhuǎn)身丶即天涯閱讀 294評論 0 0
  • 數(shù)組類型和數(shù)組引用變量詳解 數(shù)組類型為什么要用數(shù)組?Java數(shù)組的兩大特征:定義數(shù)組時,不能指定數(shù)組的長度變量分為...
    Ansaxnsy閱讀 2,912評論 2 3
  • 05.01_Java語言基礎(chǔ)(數(shù)組概述和定義格式說明)(了解) A:為什么要有數(shù)組(容器)為了存儲同種數(shù)據(jù)類型的多...
    苦笑男神閱讀 632評論 0 0