简体   繁体   中英

Java: Adding a user input to while loop

I'm trying to put a while loop in PlayerOne class, where it would be possible with the user input to choose a profession of a player. I'm not sure how to get it to work. Can you give me a suggestion or a hint? Thank you, (I suppose you don't need a Player class or Main class, so I'll leave them out of the way)

Scanner scanner = new Scanner(System.in);
while (true) {
         System.out.println("Choose your profession: \n" +
        "Press 1 for a knight class\n" +
        "Press 2 for a rider class\n" +
        "Press 3 for a mage class");
    int choice = scanner.nextInt();
    scanner.nextLine();
    switch (choice) {
        case 0:
            // here I want to put an option to choose a knight by pressing number 1
            break;
        case 1:
            // an option to choose a rider by pressing number 2
            break;
case 1:
            // an option to choose a mage by pressing number 3
            break;

I think you need a stop condition for your while when someone choose a valid profession, like this:

Scanner scanner = new Scanner(System.in);
String profession = null;
while (profession == null) {
    System.out.println("Choose your profession: \n" +
        "Press 1 for a knight class\n" +
        "Press 2 for a rider class\n" +
        "Press 3 for a mage class");
    int choice = scanner.nextInt();
    scanner.nextLine();
    switch (choice) {
        case 1:
            profession = "knight";
            break;
        case 2:
            profession = "rider";
            break;
        case 3:
            profession = "mage";
            break;
        default:
            System.out.println("Invalid option");
            profession = null;
            break;
    }
}
System.out.println("You selected: "+profession+" class.");
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String profession= null;
    while (profession == null) {
        System.out.println("Choose your profession: \n" +
                "Press 1 for a knight class\n" +
                "Press 2 for a rider class\n" +
                "Press 3 for a mage class");
        String choice = scanner.nextLine();

        if (choice.equals("1")){
            profession = "knight";
            System.out.println("You selected: "+profession+" class.");
        }else if (choice.equals("2")){
            profession = "rider";
            System.out.println("You selected: "+profession+" class.");
        }else if (choice.equals("3")){
            profession = "mage";
            System.out.println("You selected: "+profession+" class.");
        }else {
            System.out.println("invaild option");
        }
    }
    
}

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