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
Aucun commentaire:
Enregistrer un commentaire