java数组如何循环添加元素

Python011

java数组如何循环添加元素,第1张

java数组循环添加元素,实例如下:

public class ceshi {

public static void main(String[] args) throws Exception {

int[] intArray = new int[10]//新建一个int类型数组

for (int i = 0 i < 9 i++) {

intArray[i] = i

System.out.println("循环给int数组赋值,打印出来的值为  " + intArray[i])

}

}

}

运行结果为:

有两种方法:

1. 使用三层循环遍历多维数组

public class Ransack {

public static void main(String[] args) {

int array[][][] = new int[][][]{ // 创建并初始化数组

{ { 1, 2, 3 }, { 4, 5, 6 } },

{ { 7, 8, 9 }, { 10, 11, 12 } },

{ { 13, 14, 15 }, { 16, 17, 18 } }

}

array[1][0][0] = 97 // 改变指定数组元素

for (int i = 0i <array.lengthi++) { // 遍历数组

for (int j = 0j <array[0].lengthj++) {

for (int k = 0k <array[0][0].lengthk++) {

System.out.print(array[i][j][k] + "\t")

}

System.out.println() // 输出一维数组后换行

}

}

}

2.使用foreach 遍历三维数组

public class ForEachRansack {

public static void main(String[] args) {

int array[][][] = new int[][][]{ // 创建并初始化数组

{ { 1, 2, 3 }, { 4, 5, 6 } },

{ { 7, 8, 9 }, { 10, 11, 12 } },

{ { 13, 14, 15 }, { 16, 17, 18 } }

}

for (int[][] is : array) { // 遍历数组

for (int[] is2 : is) {

for (int i : is2) {

System.out.print(i + "\t")

}

System.out.println() // 输出一维数组后换行

}

}

}

}