簡體   English   中英

嘗試為 Java 中的游戲制作“重玩”功能

[英]Trying to make a "Play Again" feature for a game in java

在一個簡單的數學游戲中嘗試重玩功能,當用戶回答 10 個問題時,它會詢問用戶是否願意重玩是/否,但當您輸入任何響應時,它會結束。 當用戶鍵入 Y(是)時,我需要添加什么才能使其再次運行游戲?

public class Main {

    public static void main(String[] args) {
        Question q1 = new Question(5); // to create a new object
        Scanner input = new Scanner(System.in);

        for (int i = 0; i < 10; i++) {
            q1.showQuestion2();
            q1.checkAnswer(input.nextInt());
        }

        boolean play = true;
        while (play){
            play = input.nextLine().trim().equalsIgnoreCase("y");
            System.out.println("Would ou like to play again Y/N?");
            String next = input.next();
        }
    }
}

你已經非常接近答案了。 你只需要

  1. 將問題和答案移動到循環中
  2. 檢查下一個變量是否為“Y”。

如果不是,則將 play 設置為 false。

boolean play = true;
do {

   Question q1 = new Question(5); // to create a new set of question everytime in the loop.
   Scanner input = new Scanner(System.in);
    for (int i = 0; i < 10; i++) {
        q1.showQuestion2();
        q1.checkAnswer(input.nextInt());

         input.nextLine(); //add this line to "flush" the \n 
    }

    System.out.println("Would ou like to play again Y/N?");  
    //using nextLine() instead of next() -> so that the "/n" in the scanner buffer is cleared.
    String next = input.nextLine().trim() ; //remove spaces 
    play = next.startsWith("y") || next.startsWith("Y");
}while(play);

您可以將具有播放邏輯的代碼移動到一個新方法,並在用戶輸入Y時調用該方法。 這提高了代碼的可讀性

public static void playGame()
{
    //Logic for playing the game goes here
    Question q1 = new Question( 5 ); // to create a new object
    Scanner input = new Scanner( System.in );
    for ( int i = 0; i < 10; i++ ) {
        q1.showQuestion2();
        q1.checkAnswer( input.nextInt() );
    }
}

並更改 main 方法以有條件地調用playGame()

public static void main( String[] args )
{
    boolean continuePlaying = true;
    while ( continuePlaying ) {
        playGame();
        System.out.println( "Would ou like to play again Y/N?" );
        continuePlaying = input.nextLine().trim().equalsIgnoreCase( "y" );
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM