Java:如何询问用户是否要再次玩

时间:2019-10-18 17:11:21

标签: java loops do-while

您如何询问用户是否要再次玩。 我必须要求用户为此输入一个字符-“ y”或“ n”(确保它不区分大小写)

如果用户输入“ y”,那么我希望它循环显示问题“您要玩几轮”,然后是“ [代码块]”。

    //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');
    }

2 个答案:

答案 0 :(得分:0)

使用while循环检查用户是否要再次播放,您处在正确的轨道上,但是您在错误的位置开始循环。您的while循环应该在您要重复的任何操作之前开始。所以伪代码大概是:

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

此外,从不以分号结束条件。它不会编译。

答案 1 :(得分:0)

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);     
}