[英]Random Integers of int elements in Array
Please guys, I am still learning Java and not familiar with some of its iteration techniques yet.拜托了,我还在学习 Java,还不熟悉它的一些迭代技术。 I want to iterate through this array int[] lst = {34, 23, 7, 14, 10} so that it must generate random numbers between each elements in the array.
我想遍历这个数组 int[] lst = {34, 23, 7, 14, 10} 以便它必须在数组中的每个元素之间生成随机数。 Eg.
例如。 It must be able to list random values between 34 and 23, 23 and 7, 7 and 14, and 14 and 10. Please I need help terribly as I have been working for it ever since last night till morning.
它必须能够列出 34 和 23、23 和 7、7 和 14、14 和 10 之间的随机值。我非常需要帮助,因为我从昨晚到早上一直在为它工作。 My terrible code is pasted below.
我可怕的代码粘贴在下面。
public class ArrayRange {
public static void main(String[] args) {
Random rand = new Random();
int[] lst = {34, 23, 7, 14, 10};
for(int i = 0; i < lst.length; i++){
if ( i == 0){
int result = rand.nextInt(lst[i])+1;
System.out.println(result);
}
else {
int max = lst.length - 1;
System.out.println(rand.nextInt(max - lst[i])+ 1);
}
}
}
}
Try this:尝试这个:
public class ArrayRange {
public static void main(String[] args) {
Random rand = new Random();
int[] lst = {34, 23, 7, 14, 10};
for(int i = 0; i < lst.length-1; i++){
int val = rand.nextInt(Math.max(lst[i], lst[i+1]) - Math.min(lst[i], lst[i+1])) + Math.min(lst[i], lst[i+1]);
System.out.println("(" + lst[i] + ", " + lst[i+1] + "):" + val);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.