use*_*902 1 java arrays random
public class Tester {
public static int randomInt(int low, int high){//this method finds a random integer in between the range of low and high.
return (int)(Math.random()*(high-low)+low);
}
public static int[] randomArray(int[] a){//this method enters those random integers into an array of 100 length.
for(int i = 0;i<a.length; i++){
a[i] = randomInt(0, 100);
}
return a;
}
public static int[] multiple(int[] a, int n){//this method replaces the input array with a new array consisting of (random) multiples of n
int[] x = new int[100];
for(int i = 0; i<a.length; i++){
x[i] = randomArray(a)[i]*n;
}
return x;
}
public static void list(int[] ints){//this method lists(prints) each indexes in the array in a i(index):ints[i](the random value) format.
for(int i = 0; i<ints.length; i++){
System.out.println(i+":"+ints[i]);
}
}
public static void main(String[] args) {
int[] a = new int[100];
list(a);// this will yield 1~99:0 since the indexes in the array weren't assigned any values.
}
}
Run Code Online (Sandbox Code Playgroud)
然而.....
public static void main(String[] args) {
int[] a = new int[100];
int[] b = multiple(a, 2);
list(a);//this would instead give me a list of random numbers(0~99:random value) that are not even multiples of 2.
Run Code Online (Sandbox Code Playgroud)
这没有意义,因为multiple()
方法不应该修改它的值int[] a
.数组a的长度为100,默认情况下每个索引为0.然后,数组a直接进入list()
方法,multiple()
无论如何不应该改变它.由它给出的新数组multiple()
存储在数组中b
.为什么会这样?}
multiple
调用randomArray
,反过来,修改作为参数传递的数组:
a[i] = randomInt(0, 100);
Run Code Online (Sandbox Code Playgroud)
解决此问题的一种方法是完全删除此方法,因为您总是访问数组的单个成员,并直接调用randomInt
:
public static int[] multiple(int[] a, int n){
int[] x = new int[100];
for(int i = 0; i < a.length; i++) {
x[i] = randomInt(0, 100) * n; // Here
}
return x;
}
Run Code Online (Sandbox Code Playgroud)