简体   繁体   中英

Random Integers of int elements in Array

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);
            }
        } 
    } 
}

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);
        } 
    } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM