【发布时间】:2019-11-08 17:15:26
【问题描述】:
我想通过多次使用 Math.random 来打乱数组,但我不知道如何将随机整数放入打乱中并多次使用随机整数。
public static void scramble(int[] array){
for(int i = 0 ; i < array.length - 1; i++){
int temp = array[i];
array[i] = array[random];
array[random] = temp;}}
public int random (){
return (int)(Math.random() *9) + 1;}
输出
100 101 102 103 104 105 106 107 108 109 //Default
101 104 102 105 103 106 108 109 100 107 //Scrambled
100 101 102 103 104 105 106 107 108 109//Then sorted
整个驱动程序
import java.lang.Math;
public class Driver03{
public static void main(String[] args){
int[] array = {100, 101, 102, 103, 104, 105, 106, 107, 108, 109};
print(array);
scramble(array);
print(array);
print(array);}
public static void print(int[] array){
for(int x = 0; x < array.length; x++){
System.out.print(" " + array[x]);}
System.out.println("");}
public static void scramble(int[] array){
int random = random();
for(int i = 0 ; i < array.length - 1; i++){
int temp = array[i];
array[i] = array[random];
array[random] = temp;}}
public int random (){
return (int)(Math.random() *9) + 1;}
}
【问题讨论】:
-
你能解释得更好吗?举例说明您的输入和预期输出也很有用
-
要注意的一件事是您的 random() 函数返回一个介于 1 和 9 之间的值,如果传递给 scramble() 函数的数组长度不是至少 10 个元素,您可以接收索引超出范围异常。您可能需要更新 random() 函数以接受数组中要加扰的元素数量的参数。