How can I correctly use random seeds in Java for consistent results?

0
5
Asked By QuestionSeeker42 On

I'm having some trouble with my Java assignments related to generating random numbers. My code works fine on my computer, but it produces different results when submitted for grading. Here's the code I have:

```java
import java.util.*;
import java.util.Random;

public class GuessANumber02 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a seed:");
int seed = sc.nextInt();
System.out.println("nWelcome!");
Random rand = new Random(seed);
int tries = 0;
int win = rand.nextInt(101);
System.out.println("Please enter a number between 1 and 100:");
for (int i = 0; i > -1; i++) {
tries++;
int guess = sc.nextInt();
if (guess == win) {
break;
} else if (guess < win) {
System.out.println("nToo low. Guess again:");
} else {
System.out.println("Too high. Guess again:");
}
}
System.out.println("Congratulations. You guessed correctly!");
System.out.println("You needed " + tries + " guesses.");
}
}
```

The issue is that the grading system seems to expect specific outputs based on the random number generation. My professor hasn't been very helpful with this issue. Can someone explain what the proper method is for seeding random elements in Java, especially in a way that will be consistent for grading or testing?

1 Answer

Answered By CuriousCoder88 On

It sounds like the grading system might be using a different version of Java or a different implementation of the Random class. Make sure you're using the exact seed value that the assignment specifies; they usually provide that in the instructions. If you consistently use that seed, your outputs should match what the system expects.

QuestionSeeker42 -

Right, they do give specific seed values sometimes. I notice that sometimes the expected numbers differ, which makes it hard for me to figure out the correct method for seeding. What exactly should I aim for?

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.