数组;相同数据类型变量的集合。
示例代码:
一维数组:
- class ArrayDemo{
- public static void main(String args[]){
- int i;
- int sample[]=new int[10]; //创建一个有10个元素的int数组
- for(i=0;i<10;i++){ //为数组元素赋值,数组索引从0开始
- sample[i]=i;
- }
- for(i=0;i<sample.length;i++){ //打印数组元素,下边从0开始 可以用.length访问数组长度
- System.out.println("sample["+ i +"]="+ sample[i]);
- }
- for(int x : sample){ //for-each循环输出一维数组元素
- System.out.print("x="+ x +"\t");
- }
- System.out.println("\nsum="+ sum);
- }
- }
- }
二维数组:二维数组可以理解为一维数组的列表
- class TwoArray{
- public static void main(String args[]){
- int twoarray[][] = new int[3][4]; //创建一个三行四列的二维数组
- for(int i=0;i<twoarray.length;i++){ //行
- for(int j=0;j<twoarray[i].length;j++){ //列
- twoarray[i][j] = (4*i) + j +1; //为数组元素赋值
- System.out.print(" "+ twoarray[i][j]); //打印输出数组元素
- }
- System.out.println(); //换行
- }
- for(int x[]:twoarray){ //for-each打印二维数组元素
- for(int y:x){
- System.out.print("y="+ y +"\t");
- }
- System.out.println();
- }
- }
- }