运用java安排一个一维数组存放20个不重复的整数,产生一个新的数组存放原来数组元素乱序处理后的数据。分别打印出新旧数组。
时间: 2023-06-26 11:06:37 浏览: 101
以下是一个参考代码:
```java
import java.util.Arrays;
import java.util.Random;
public class ShuffleArray {
public static void main(String[] args) {
int[] original = new int[20];
Random random = new Random();
// 初始化原始数组
for (int i = 0; i < 20; i++) {
original[i] = i + 1;
}
// 随机交换数组元素
for (int i = 0; i < 20; i++) {
int j = random.nextInt(20);
int temp = original[i];
original[i] = original[j];
original[j] = temp;
}
// 输出原始数组和乱序后的数组
System.out.println("Original array: " + Arrays.toString(original));
int[] shuffled = Arrays.copyOf(original, 20);
Arrays.sort(shuffled);
System.out.println("Shuffled array: " + Arrays.toString(shuffled));
}
}
```
运行结果:
```
Original array: [19, 4, 16, 5, 14, 8, 6, 7, 10, 12, 11, 3, 1, 17, 9, 13, 18, 2, 20, 15]
Shuffled array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
```
阅读全文