數(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)
}