简体   繁体   中英

Java: How to ask the user if he/she wants to play again

How do you ask the user if he/she wants to play again. I have to ask the user to enter a char for this – 'y' or 'n' (Making sure this is not case sensitive)

if the user inputs 'y', then I want it to loop the question "How many rounds would you like to play" and then the "[block of code]".

    //asks user for their name
    System.out.println("\nWhat is your name?");
    name = in.nextLine();

    //asks user the number of rounds they want to play
    System.out.println("How many rounds would you like to play?");
    numRound = in.nextInt();

    char cont = 'y';

    do {
          [block of code ]
        }

    } while (roundnum <= numRound);     
    System.out.println("Would you like to play again? (y/n)");
    cont = in.next().charAt(0);
    while (cont == 'y');
    }

You're on the right track using a while loop to check for whether the user wants to play again, but you're starting the loop at the wrong place. Your while loop should begin just before any actions you want repeated. So the pseudocode would be roughly:

while (cont == 'y'){
    //Enter game code here
    System.out.println("Would you like to play again? (y/n)");
    cont = in.next().charAt(0);
}

Also, never end a conditional with a semicolon. It won't compile.

play()

while(1) {
    System.out.println("Wanna play again? (y/N): ")
    choice = in.nextChar();

switch(choice) {
    case 'y':
    case 'Y':
        play();
        break;
    case 'n':
    case 'N:
        System.exit(0);
    default:
        System.out.println("Try again");
}

}


void play() {
    //asks user the number of rounds they want to play
    System.out.println("How many rounds would you like to play?");
    numRound = in.nextInt();

    char cont = 'y';

    do {
          [block of code ]
        }

    } while (roundnum <= numRound);     
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM