gpt4 book ai didi

java - 整数数组不会打印

转载 作者:行者123 更新时间:2023-12-02 04:45:51 25 4
gpt4 key购买 nike

我创建了这个方法randomInt ,给出一个介于 -5 和 15 之间的随机数。我创建了另一个方法 randomIntArray调用 randomInt ,在循环中,并将随机整数存储到数组中。但是,当我尝试打印它时,它只返回 ArrayIndexOutOfBoundsException

public static int randomInt(int low, int high) {
double e;
double x = Math.random();
e = low + x * (high - low);
return (int) e;
}

public static int[] randomIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = randomInt(-5, 15); //"-5&15 are the lower and upper bounds of the random number array
}
return a;
}

randomInt ,当我没有将返回值转换为 int 时,它有效,但是我需要它返回 int让数组正常工作。

最佳答案

调用 randomIntArray(number) 后检查您的打印代码;

/**
* @param args the command line arguments
*/
public static void main(String[]args) {
int[] myArray = randomIntArray(10);

// Manual iteration through your array
for (int i = 0; i < myArray.length; i++) {
System.out.print(myArray[i] + " ");
}
System.out.println("");

// Use of Arrays class to print your array
System.out.println(Arrays.toString(myArray));
}

public static int randomInt(int low, int high) {
double e;
double x = Math.random();
e = low + x * (high - low);
return (int) e;
}

public static int[] randomIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = randomInt(-5, 15);
}//"-5&15 are the lower and upper bounds of the random number array
return a;
}

结果:

enter image description here

关于java - 整数数组不会打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29659158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com