my question; why is my Java code outputting a 'random' number, as the same? - Almost like the random gets stored into the variable.
I am creating a basic higher or lower game, of which displays a card number, and user has to choose whether he/she wants to go higher or lower.
Here is my written code:
String guess;
String choice;
String choice2;
String sameChoice;
String sameChoice2;
boolean correctGuess = true;
boolean replay = true;
Random rand = new Random();
Scanner scan = new Scanner(System.in);
byte card = (byte) (rand.nextInt(13 - 0) + 1);
byte card2 = (byte) (rand.nextInt(13 - 0) + 1);
byte card3 = (byte) (rand.nextInt(13 - 0) + 1);
while (replay) {
System.out.println("Card is: " + card);
do {
System.out.printf("(H)igher or (L)ower: ");
guess = scan.nextLine();
if(guess.equals("H") || guess.equals("h")) {
System.out.println("Card is: " + card2);
if(card2 < card) {
System.out.printf("Card is lower, you lose - play again? Y/N : ");
choice = scan.nextLine();
if(choice.equals("Y") || choice.equals("y")) {
replay = true;
break;
}
else if(choice.equals("N") || choice.equals("n")) {
System.out.println("\nThank you for playing.");
replay = false;
break;
}
}
else if(card2 == card) {
System.out.printf("Numbers are the same, draw! - would you like to play again? Y/N : ");
sameChoice = scan.nextLine();
if(sameChoice.equals("Y") || sameChoice.equals("y")) {
correctGuess = false;
replay = true;
break;
}
else if(sameChoice.equals("N") || sameChoice.equals("n")) {
System.out.println("\nThank you for playing.");
replay = false;
break;
}
}
else if(card2 > card) {
correctGuess = true;
replay = false;
continue;
}
}
else if(guess.equals("L") || guess.equals("l")) {
System.out.println("Card is: " + card3);
if(card3 > card) {
System.out.printf("Card is higher, you lose - play again? Y/N : ");
choice2 = scan.nextLine();
if(choice2.equals("Y") || choice2.equals("y")) {
correctGuess = false;
replay = true;
break;
}
else if(choice2.equals("N") || choice2.equals("n")) {
System.out.println("\nThank you for playing.");
replay = false;
break;
}
}
else if(card3 == card) {
System.out.printf("Numbers are the same, draw! - would you like to play again? Y/N : ");
sameChoice2 = scan.nextLine();
if(sameChoice2.equals("Y") || sameChoice2.equals("y")) {
correctGuess = false;
replay = true;
break;
}
else if(sameChoice2.equals("N") || sameChoice2.equals("n")) {
System.out.println("\nThank you for playing.");
replay = false;
break;
}
}
else if(card3 < card) {
correctGuess = true;
replay = false;
continue;
}
}
scan.close();
} while(correctGuess);
The output of this comes out like this:
Card is: 3
(H)igher or (L)ower: h
Card is: 11
(H)igher or (L)ower: h
Card is: 11
(H)igher or (L)ower: h
Card is: 11
(H)igher or (L)ower: h
Card is: 11
(H)igher or (L)ower: h
Card is: 11
(H)igher or (L)ower:
As you can see, whenever i wanted to choose "Higher" It just repeats '11' even though my random generator is limited to 13.
Thank you.
Aucun commentaire:
Enregistrer un commentaire