I am a beginner in programming, currently learning java. As a part of my practice, I have created the below code, which is simply a game asking the user to guess the number generated randomly by the Computer, if the player guesses it correctly, the score increases by 5. The problem is that my Random Number generator every time generated the same number, no randomness at all,I want to solve this problem. And also I want a more intuitive approach for my this code. the code is mentioned below:
public static void main(String... args){
System.out.println("\nGuessNumber is a game, in which the player is required to guess the number\n"
"generated randomly by the computer. If the player guesses it right his score\n"
"is increased to 5, no score is cut when losing. The number will be from 1 to 6\n"
"inclusive.\n");
Scanner scan = new Scanner(System.in);
char input;
int randomNumber;
int playerScore =0 ;
//int roundCounter = 0;
do{ System.out.print("Press 'r' to play and 'q' to quit: ");
input = scan.next().charAt(0);
switch (input){
case 'r':
System.out.print("A random number is generated for you, guess what it is: ");
int answer = scan.nextInt();
if(answer == (randomNumber = generateRandom())){
System.out.print("Congrats! that was absolutely right guess, ");
playerScore = 5;
}else{
System.out.print("Oops!, wrong guess, right answer is " randomNumber ", ");
}
break;
case 'q':
System.out.println("Bye Bye!");
break;
default:
System.err.print("Enter a valid input: ");
break;
}
}while(input != 'q');
System.out.println("You scored " playerScore);
}
private static int generateRandom(){
Random random = new Random(1);
return random.nextInt(7);
}
and a sample output:
Edit: If you can provide a better approach to write this code, please suggest me
CodePudding user response:
As commented, do not set the seed to the same number if you want different results. Same seed yields same results.
Your code new Random(1) results in a number generator that generates the same sequence of outputs. Instead, call the no-arg constructor. Change this:
Random random = new Random(1);
… to this:
Random random = new Random();
The Javadoc for the no-arg constructor promises:
This constructor sets the seed of the random number generator to a value very likely to be distinct from any other invocation of this constructor.
CodePudding user response:
You can simply remove the seed number inside Random() constructor, and your code will be good to go. Just change your generateRandom() method.
private static int generateRandom() {
Random random = new Random();
return random.nextInt(17);
}
Or you can use this technique in genrateRandom() method
private static int generateRandom() {
int maximumnumber =17, minimumnuber =0;
int randomnum = (int)(Math.random()*(maximumnumber-minimumnuber 1) minimumnuber);
return randomnum;
}

