Reputation: 1
Please guys, I am still learning Java and not familiar with some of its iteration techniques yet. 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. 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. 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);
}
}
}
}
Upvotes: 0
Views: 63
Reputation: 19
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);
}
}
}
Upvotes: 1