简体   繁体   English

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

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

I'm making a simple gradebook that's supposed to generate random numbers for each assignment for each student. 我正在制作一个简单的成绩簿,该成绩簿应该为每个学生的每次作业生成随机数。 It generates random numbers, but the numbers are the same each loop. 它生成随机数,但每个循环的数字相同。 Here's the code I have so far: 这是我到目前为止的代码:

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

I get 540 points for each student, but I should be getting a random value between 300 and 600 for each student each time it loops. 我为每个学生获得540分,但是每次循环时,我应该为每个学生获得300到600之间的随机值。

Thanks for anything! 谢谢你!

Place your instance of Random outside the loop. 将您的Random实例放置在循环之外。 What you're doing is creating a new instance of random each iteration, with the same seed. 您正在执行的操作是使用相同的种子在每次迭代中创建一个新的随机实例。 The seed determines which values are going to get generated, and with the same seed, you'll get the same numbers each time. 种子确定将要生成的值,并且使用相同的种子,每次将获得相同的数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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