如何使用带循环的种子生成不同的随机数?

问题描述 投票:0回答:1

我正在制作一本简单的成绩单,它应该为每个学生的每个作业生成随机数。它生成随机数,但每个循环的数字相同。这是我到目前为止的代码:

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之间的随机值。

谢谢!

java random
1个回答
3
投票

将你的Random实例放在循环外面。你正在做的是使用相同的种子在每次迭代中创建一个随机的新实例。种子确定要生成哪些值,并且使用相同的种子,每次都会得到相同的数字。

© www.soinside.com 2019 - 2024. All rights reserved.