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.
}
}
无论其.....
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.
这没有意义,因为multiple()
方法不应该修改int[] a
的值。数组a的长度为100,默认情况下每个索引为0。然后,数组a直接进入list()
方法,无论如何都不应该被multiple()
改变。 multiple()
给出的新数组存储在数组b
中。为什么会这样?
}
答案 0 :(得分:5)
multiple
调用randomArray
,然后修改作为参数传递的数组:
a[i] = randomInt(0, 100);
解决此问题的一种方法是完全删除此方法,因为您始终只访问数组的单个成员,并直接调用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;
}