int arr[][] = new int[2][3]; arr[1][1] = 8;
1.执行 int arr[][] = new int[3][];
2. 遍历数组并赋值
package Array; public class TwoDiemantionalArray { public static void main(String[] args) { int arr[][] = new int[3][]; for (int i = 0; i < arr.length; i++) { arr[i] = new int[i + 1]; //遍历数组,赋值 for (int j = 0; j < arr[i].length; j++) { arr[i][j] = i + 1; } } //遍历输出 for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++){ System.out.print(arr[i][j] + " "); } System.out.println(); } } }
结果:
1
2 2
3 3 3
package Array; public class YangHui { public static void main(String[] args) { int arr[][] = new int[10][]; for (int i = 0; i < arr.length; i++) { arr[i] = new int[i + 1]; for (int j = 0; j < arr[i].length; j++) { // if (i == 0 | j ==0) // arr[i][j] = 1; // else if (i == j) // arr[i][j] = 1; if (j == 0 | j == arr[i].length - 1) arr[i][j] = 1; else arr[i][j] = arr[i - 1][j] + arr[i - 1][j - 1]; System.out.print(arr[i][j] + "\t"); } System.out.println(); } } }
结果
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
在数组中插入一个数值,使得数组成按照从小到大的顺序排列
import java.util.Scanner; public class AsdArray { public static void main(String[] args) { int arr[] = {10,12,45,90}; Scanner input = new Scanner(System.in); // int addNum = input.nextInt(); int addNum = 200; int index = -1; //锁定位置 for (int i = 0; i < arr.length; i++) { if (arr[i] >= addNum) { index = i; break; } } if (index == -1) index = arr.length; // System.out.println(index); // 扩容 int arr1[] = new int[arr.length + 1]; //插入 arr1[index] = addNum; for (int i = 0; i < index; i++) { arr1[i] = arr[i]; } for (int i = index + 1; i < arr1.length; i++) { arr1[i] = arr[i - 1]; } arr = arr1; for (int i: arr) { System.out.print(i + " "); } } }
结果
10 12 45 90 200