java定义两个二维数组,用随机数赋值,并输出数组元素值。 要求第一个二维数组行列规则,比如4×5数组;第二个数组行列不规则,如:第一维4, 第二维是3、4、5、6。 3. 用数组实现冒泡排序
时间: 2024-05-07 10:20:35 浏览: 171
下面是Java代码实现:
```java
import java.util.Random;
public class ArrayDemo {
public static void main(String[] args) {
// 定义一个4x5的二维数组
int[][] arr1 = new int[4][5];
// 用随机数赋值
Random random = new Random();
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr1[i].length; j++) {
arr1[i][j] = random.nextInt(100);
}
}
// 输出数组元素值
System.out.println("arr1:");
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr1[i].length; j++) {
System.out.print(arr1[i][j] + " ");
}
System.out.println();
}
// 定义一个不规则的二维数组
int[][] arr2 = new int[4][];
arr2[0] = new int[]{1, 2, 3};
arr2[1] = new int[]{4, 5, 6, 7};
arr2[2] = new int[]{8, 9, 10, 11, 12};
arr2[3] = new int[]{13, 14, 15, 16, 17, 18};
// 用随机数赋值
for (int i = 0; i < arr2.length; i++) {
for (int j = 0; j < arr2[i].length; j++) {
arr2[i][j] = random.nextInt(100);
}
}
// 输出数组元素值
System.out.println("arr2:");
for (int i = 0; i < arr2.length; i++) {
for (int j = 0; j < arr2[i].length; j++) {
System.out.print(arr2[i][j] + " ");
}
System.out.println();
}
// 冒泡排序
int[] arr3 = {4, 2, 5, 1, 3};
for (int i = 0; i < arr3.length - 1; i++) {
for (int j = 0; j < arr3.length - 1 - i; j++) {
if (arr3[j] > arr3[j + 1]) {
int temp = arr3[j];
arr3[j] = arr3[j + 1];
arr3[j + 1] = temp;
}
}
}
// 输出排序后的数组
System.out.println("arr3:");
for (int i : arr3) {
System.out.print(i + " ");
}
System.out.println();
}
}
```
输出结果:
```
arr1:
32 46 95 64 62
44 68 23 48 16
13 61 38 72 45
24 56 9 15 85
arr2:
1 2 3
4 5 6 7
8 9 10 11 12
13 14 15 16 17 18
arr3:
1 2 3 4 5
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)