samedi 12 novembre 2016

how can i repeat a specific part of a Loop in Java

my question is how am I able to repeat part of a do while loop, if an if-statement's output is true?

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 what i am trying to achieve:

public static void main(String[] args) {
    int card = 0;
    int card2 = 0;
    String guess;
    String choice;

    boolean correctGuess = true;

    do {

        Random rand = new Random();
        Scanner scan = new Scanner(System.in);

        card = rand.nextInt(13 - 0) + 1; 
        card2 = rand.nextInt(13 - 0) + 1;

        System.out.println("Card is: " + card);
        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")) {
                    continue;
                }
                else if(choice.equals("N") || choice.equals("n")) {
                    System.out.println("\nThank you for playing.");
                    break;
                }
            }
            else if(card2 > card) {
                continue;
            }
        } scan.close();
    } while(correctGuess);

My aim is for when the last "else if" statement's output is true, then repeat the while loop, here is what happens currently:

Card is: 10
(H)igher or (L)ower: h
Card is: 2
Card is lower, you lose - play again? Y/N : y
Card is: 2
(H)igher or (L)ower: h
Card is: 10
Card is: 2
(H)igher or (L)ower: 

As you c an see from the last 3 lines, it outputs "Card is:" twice, i only want it once? Thankyou

Aucun commentaire:

Enregistrer un commentaire