簡體   English   中英

如何使用帶有循環的種子生成不同的隨機數?

[英]How can I generate different random numbers using a seed with a loop?

我正在制作一個簡單的成績簿,該成績簿應該為每個學生的每次作業生成隨機數。 它生成隨機數,但每個循環的數字相同。 這是我到目前為止的代碼:

import java.util.Random;
import java.util.Scanner;

public class Testing {
public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    String choice = "y";
    while (choice == "y")   { 

        System.out.println("Please enter a number for the random number generator seed:");
        //User input for seed
        int seed = sc.nextInt(); 
        //Initializing Seed
        Random randomSeed = new Random(seed);

        //Prompting for number of students
        System.out.println("Please enter the no of students for whom you have grade information: "); 
        //User input for number of students
        int numberOfStudents = sc.nextInt();

        String homework = "HW";

        System.out.printf("%16s", homework);
        System.out.println("\n");

        //Finding random value for Homework.
        int randomHomework = randomSeed.nextInt(((600-300) + 1) + 300); 

        //Creates an array that has 7 rows for points
        //Will eventually add more values into array
        int points [][] = new int[6][3]; 

        //for loop that starts at 1 and prints number of students user entered
        for (int i = 0; i < numberOfStudents; i++) {
            System.out.print("Student #" + (i + 1) + "    ");

            points[0][2] += randomHomework;
            System.out.print(randomHomework + "    ");

            System.out.println("\n");
            }//End of for loop

        choice = sc.nextLine().toUpperCase();
        }//End of while loop
    }
}

我為每個學生獲得540分,但是每次循環時,我應該為每個學生獲得300到600之間的隨機值。

謝謝你!

將您的Random實例放置在循環之外。 您正在執行的操作是使用相同的種子在每次迭代中創建一個新的隨機實例。 種子確定將要生成的值,並且使用相同的種子,每次將獲得相同的數字。

暫無
暫無

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

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