簡體   English   中英

數組中int元素的隨機整數

[英]Random Integers of int elements in Array

拜托了,我還在學習 Java,還不熟悉它的一些迭代技術。 我想遍歷這個數組 int[] lst = {34, 23, 7, 14, 10} 以便它必須在數組中的每個元素之間生成隨機數。 例如。 它必須能夠列出 34 和 23、23 和 7、7 和 14、14 和 10 之間的隨機值。我非常需要幫助,因為我從昨晚到早上一直在為它工作。 我可怕的代碼粘貼在下面。

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

嘗試這個:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM