简体   繁体   中英

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.

Thanks for anything!

Place your instance of Random outside the loop. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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