簡體   English   中英

Java:在最小值和最大值之間生成隨機數

[英]Java :Generate random numbers between minimum and a maximum values

這是我堅持的練習:

詢問用戶想要生成的最小、最大(包括)和多少(計數)隨機數。 確保最小值不大於最大值並且計數不為負。 如果輸入無效,則顯示錯誤消息。 如果一切正常,則生成隨機數並將它們打印出來,以逗號分隔在一行中。

我以多種方式編寫了代碼。 我永遠無法獲得for循環來打印隨機數。

package randnumsmany;

import java.util.Scanner;

public class RandNumsMany {

    public static double getRandomNumber(int min, int max) {
        return (int) ((Math.random() * (max - min)) + min);
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter minimum :");
        int min = input.nextInt();

        System.out.println("Enter maximum :");
        int max = input.nextInt();

        System.out.println("Enter number generated :");
        int num = input.nextInt();

        int[] rand = new int[num];

        for (int i = 0; i == num - 1; i++) {
            rand[i] = (int) getRandomNumber(min, max);
        }
        for (int i = 0; i == num - 1; i++) {
            System.out.println(rand[i]);
        }

        System.out.println("How many generated: " + num);    
    }
}
  1. 你不需要它的數組。 您可以在計算時簡單地打印所有數字。 由於您必須以逗號分隔打印它們,因此您可以打印除最后一個后跟一個逗號之外的所有內容,然后打印不帶逗號的最后一個。
  2. 此外,您可以使用無限循環來檢查輸入的有效性。 如果輸入有效,您可以中斷循環,否則由於循環,將再次請求輸入。
  3. 此外,由於最大值需要包含在內,計算隨機數的公式應該是(int) (Math.random() * (max - min + 1) + min)

演示:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int min, max, num;

        System.out.print("Enter minimum: ");
        min = input.nextInt();

        while (true) {
            System.out.print("Enter maximum: ");
            max = input.nextInt();

            if (min > max) {
                System.out.println("Minimum can not be larger than maximum");
            } else {
                break;
            }
        }

        while (true) {
            System.out.print("Enter number generated: ");
            num = input.nextInt();
            if (num < 0) {
                System.out.println("The count can not be negative");
            } else {
                break;
            }
        }

        // Print all but the last number followed by a comma
        for (int i = 1; i <= num - 1; i++) {
            System.out.print(getRandomNumber(min, max) + ", ");
        }

        // Print the last number without a comma
        System.out.print(getRandomNumber(min, max));
    }

    public static int getRandomNumber(int min, int max) {
        return (int) (Math.random() * (max - min + 1) + min);
    }
}

示例運行:

Enter minimum: 10
Enter maximum: 20
Enter number generated: 20
19, 17, 13, 17, 16, 19, 12, 15, 20, 15, 17, 17, 19, 12, 13, 10, 16, 12, 14, 17

另一個示例運行:

Enter minimum: 10
Enter maximum: 5
Minimum can not be larger than maximum
Enter maximum: 20
Enter number generated: -10
The count can not be negative
Enter number generated: 5
18, 16, 11, 11, 13
// randomStream(n, min, max): e.g using stream, generate n number between min and max
// randomRandom(min, max) example of getting one random number between min and max
// randomMath(min, max): other way similar to randomRandom(min, max)
// randomThreadLocalRandom(): just for a random number without constrain
// It is effective way to use stream when many random number are needed.
    import java.util.Random;
    import java.util.concurrent.ThreadLocalRandom;
    
    public class Randomize {
        public static void main(String args[]){
            randomStream(2, 3, 10);
            randomRandom(3, 10);
            randomMath(3, 10);
        }
        
        // (generate random number between 0.0 and 1.0) * (max - min +(1 or 0)) + min
        
        // length: how much number you want to generate
        public static void randomStream( int length, int min, int max){ 
            System.out.println("using random as Stream");
            Random rand = new Random();
            int[] random = rand.ints(length, min, max).toArray(); 
            System.out.print("As integer: ");
            for(int i : random)  
                System.out.print(i+"; "); 
            System.out.println("");
            
            double[] randomD = ThreadLocalRandom.current().doubles(length, min, max).toArray();
            System.out.print("As double: "); 
            for(double d : randomD) 
                System.out.print(d+"; "); 
            System.out.println("");
        }
        
        public static void randomRandom(int min, int max){
            System.out.println("using Random");
            Random rand = new Random();
        
            int int_random = min + rand.nextInt(max-min);
            System.out.println("As integer: "+ int_random);
            
            double double_random = min + rand.nextDouble();
            System.out.println("As double: "+double_random);
        }
        
        public static void randomMath(int min, int max){
            System.out.println("using Math:");
            int random_int = (int)(Math.random() * (max - min + 1) + min);
            System.out.println("As integer: "+random_int);
            
            double random_double = Math.random() * (max - min + 1) + min; 
            System.out.println("As double: "+ random_double);
        }
        
        public static void randomThreadLocalRandom(){
            int int_random = ThreadLocalRandom.current().nextInt();  
            System.out.println("As Integers: " + int_random); 
            
            double double_rand = ThreadLocalRandom.current().nextDouble(); 
            System.out.println("As Doubles: " + double_rand); 
        }
    }
//

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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