簡體   English   中英

Java 做猜謎游戲

[英]Java do while Guessing Game

因此,對於上周我必須完成的一項作業,我必須使用 4 個 do-while 循環和 if 語句在 Java 中制作一個猜謎游戲。 我無法成功完成它,班級繼續前進,沒有提供任何幫助。 如果有人可以查看我的代碼並告訴我我可以在哪里改進它以便程序正常運行,我將不勝感激。

為了簡要描述賦值,賦值需要 4 個 do-while 循環:

  1. 主要的 do-while 循環,它包含大部分代碼並保持程序運行直到用戶想要退出
  2. 游戲 do-while 循環使游戲一直運行,直到用戶猜出正確的數字,此時它將退出。 (這部分我想不通)。
  3. 游戲循環內的數字輸入驗證 do-while 循環,可確保用戶的猜測有效。
  4. 一個非數字輸入驗證 do-while 循環,它在游戲循環之后和之外,詢問用戶是否想再次玩,並檢查有效的“Y”或“N”響應

這是我想出的:

package week4;

//Imports
import java.lang.Math;
import java.util.Scanner;


public class Lab4d {
    public static void main(String[] args) {

        //Set up scanners
        Scanner again = new Scanner(System.in);
        Scanner num1 = new Scanner(System.in);

        //Set up variables
        int userInput = 0;
        int guesses = 0;
        int min = 1;
        int max = 100;
        int range = max - min + 1;
        int randNum = (int)(Math.random() * range) + min;
        boolean valid = false;

        //Outside loop
        do{
            //Describe the game
            System.out.println("\nThis program is a guessing game.");
            System.out.println("\nThe computer will pick a random number "
                               + "between 1 and 100.");
            System.out.println("\nYou will try to guess it.");
            System.out.println("\nLet's play!");

            //Insert Game loop here
            do {
                System.out.println("\nI'm thinking of a number " +
                                   "between 1 and 100.");
                //Insert valid guess checker here
                do {
                    System.out.println("Please enter your guess: ");
                    if (num1.hasNextInt()){
                        userInput = num1.nextInt();
                        valid = true;
                    }
                    else {
                        System.out.println("Error: Please enter a whole number.\n");
                        num1.nextLine();
                    }
                }while(!valid);

                if (userInput > randNum) {
                    System.out.println("\nToo high!");
                    guesses++;
                }
                else if (userInput < randNum) {
                    System.out.println("\nToo Low!");
                    guesses++;
                }
                else if (userInput == randNum) {
                    System.out.println("You got it!");
                    System.out.println("It took you" + guesses + "tries");
                    valid = true;
                }
            }while(!valid);


            //Insert play again checker
            do {
                System.out.println("\nDo you want to play again?");
                System.out.println("\nEnter 'Y' if yes and 'N' if no.");
                String play = again.nextLine();
                if (play.equalsIgnoreCase("Y")) {
                    valid = true;
                }
                else if (play.equalsIgnoreCase("N")) {
                    valid = true;
                }

                else {
                    System.out.println("Error: Please answer with 'Y' or 'N'");
                }
            }while(!valid);

        }while(!valid);
    }
}

我感謝您的幫助!

你的問題在程序的這一部分

//Insert Game loop here
        do {
            System.out.println("\nI'm thinking of a number " +
                    "between 1 and 100.");
            //Insert valid guess checker here
            do {
                System.out.println("Please enter your guess: ");
                if (num1.hasNextInt()){
                    userInput = num1.nextInt();
                    valid = true; //>>>>> HERE YOU SET VALID TO TRUE 
                }
                else {
                    System.out.println("Error: Please enter a whole number.\n");
                    num1.nextLine();

                }

            }while(!valid);
            if (userInput > randNum) {
                System.out.println("\nToo high!");
                guesses++;
            }
            else if (userInput < randNum) {
                System.out.println("\nToo Low!");
                guesses++;
            }
            else if (userInput == randNum) {
                System.out.println("You got it!");
                System.out.println("It took you" + guesses + "tries");
                valid = true;
            }

        }while(!valid); //>>>>> AND THIS !VALID CHECK USES THE SAME "valid" boolean

所以只需像這樣使用兩個單獨的布爾值

//Imports
import java.util.Scanner;

public class Lab4d{
public static void main(String[] args) {

    // Set up scanners
    Scanner again = new Scanner(System.in);
    Scanner num1 = new Scanner(System.in);

    // Set up variables
    int userInput = 0;
    int guesses = 0;
    int min = 1;
    int max = 100;
    int range = max - min + 1;
    int randNum = (int) (Math.random() * range) + min;
    boolean valid = false;

    // Outside loop
    do {
        // Describe the game
        System.out.println("\nThis program is a guessing game.");
        System.out.println("\nThe computer will pick a random number " + "between 1 and 100.");
        System.out.println("\nYou will try to guess it.");
        System.out.println("\nLet's play!");

        // Insert Game loop here
        do {
            System.out.println("\nI'm thinking of a number " + "between 1 and 100.");
            // Insert valid guess checker here

            boolean userInputValid = false;
            do {
                System.out.println("Please enter your guess: ");
                if (num1.hasNextInt()) {
                    userInput = num1.nextInt();
                    userInputValid = true;
                } else {
                    System.out.println("Error: Please enter a whole number.\n");
                    num1.nextLine();
                }
            } while (!userInputValid);

            if (userInput > randNum) {
                System.out.println("\nToo high!");
                guesses++;
            } else if (userInput < randNum) {
                System.out.println("\nToo Low!");
                guesses++;
            } else if (userInput == randNum) {
                System.out.println("You got it!");
                System.out.println("It took you" + guesses + "tries");
                valid = true;
            }

        } while (!valid);

        // Insert play again checker
        do {
            System.out.println("\nDo you want to play again?");
            System.out.println("\nEnter 'Y' if yes and 'N' if no.");
            String play = again.nextLine();
            if (play.equalsIgnoreCase("Y")) {

                valid = true;
            }

            else if (play.equalsIgnoreCase("N")) {

                valid = true;
            }

            else {
                System.out.println("Error: Please answer with 'Y' or 'N'");
            }

        } while (!valid);

    } while (!valid);
}

}

正如信息(與您的問題沒有直接關系),請小心將整數與“==”進行比較,它僅適用於 -128 到 127 的值。(但您可以將 == 用於原始類型“int”)

https://wiki.owasp.org/index.php/Java_gotchas#Immutable_Objects_.2F_Wrapper_Class_Caching

您不需要兩個 Scanner 對象。 您可以使用單個 Scanner 對象完成整個應用程序:

Scanner input = new Scanner(System.in);

您的變量猜測,randNum,有效應主游戲循環中被初始化 這樣,當一個新的游戲開始,一個新的隨機值(randNum)獲取,有效重置為布爾值false,並猜測被重置為0。

valid = true; 位於if (num1.hasNextInt()){ ... } IF代碼塊中的Please enter your guess: prompt loop should be removed (deleted)。 這很快就說明輸入有效並允許提示循環退出。 當用戶提供與生成的randNum值匹配的正確值時,此標志才應為真。

用於檢查用戶輸入的IF語句應包含在Please enter your guess: prompt 循環中。 這允許顯示太高太低的指標,並且Please enter your guess:提示重新顯示以進行另一次猜測。

猜測變量保持不正確的計數(不夠)。 你只需要一個guesses++; 它應該直接放在用戶輸入有效性檢查IF/ELSE塊之后。

您應該輸入Do you want to play again?之前valid設置為false Do you want to play again? 提示循環。

Do you want to play again? 如果提供YN,則將有效設置為true 的提示循環。 所以主游戲循環永遠不會再通過。 因為您使用有效的布爾變量作為所有循環的條件,所以您需要確保如果提供Y (是),則有效滿足重新循環主游戲循環所需的條件(恰好是布爾假)或者在這個主游戲循環中使用不同的布爾標志(也許: boolean playAgain = false; )。 目前,如果提供了Y ,則valid應該等於falsebreak; 應該發出以退出提示循環。 因為valid是假的,所以主游戲循環會為新游戲再次迭代。 如果提供了N ,那么此時只需退出游戲。 無需退出提示循環:

 else if (play.equalsIgnoreCase("N")) {
    System.out.println("Thanks for playing...Bye Bye");
    System.exit(0);
 }

放置:

System.out.println("\nI'm thinking of a number "
                 + "between 1 and 100.");

do/while循環中是沒有意義的。 將輸出保留到控制台,但刪除do {} while(!valid); .

替代代碼可能類似於:

Scanner input = new Scanner(System.in);

//Set up variables
int userInput = 0;
int guesses;
int min = 1;
int max = 100;
int range = max - min + 1;
int randNum;
boolean valid;
boolean playAgain = false;

//Outside loop
do {
    //Describe the game
    System.out.println("\nThis program is a guessing game.");
    System.out.println("\nThe computer will pick a random number "
            + "between 1 and 100.");
    System.out.println("\nYou will try to guess it.");
    System.out.println("\nLet's play!");

    randNum = (int) (Math.random() * range) + min;
    valid = false;
    guesses = 0;

    //Insert Game loop here
    System.out.println("\nI'm thinking of a number "
            + "between 1 and 100.");
    //Insert guess and validator here
    do {
        System.out.println("Please enter your guess: ");
        if (input.hasNextInt()) {
            userInput = input.nextInt();
        }
        else {
            System.out.println("Error: Please enter a whole number.\n");
            input.nextLine();
            continue;
        }
        guesses++;
        if (userInput > randNum) {
            System.out.println("\nToo high!");
        }
        else if (userInput < randNum) {
            System.out.println("\nToo Low!");
        }
        else if (userInput == randNum) {
            System.out.println("You got it!");
            System.out.println("It took you " + guesses + " tries");
            valid = true;
        }
    } while (!valid);

    //Insert play again checker
    valid = false;
    do {
        System.out.println("\nDo you want to play again?");
        System.out.println("\nEnter 'Y' if yes and 'N' if no.");
        String play = input.nextLine();
        if (play.equalsIgnoreCase("Y")) {
            playAgain = true;
            valid = playAgain;
        }
        else if (play.equalsIgnoreCase("N")) {
            playAgain = false;
            valid = true;
        }
        else {
            System.out.println("Error: Please answer with 'Y' or 'N'");
        }
    } while (!valid);
} while (playAgain);

System.out.println("Thanks for playing...Bye Bye");

待辦事項:允許用戶隨時退出。

這是一個工作代碼

Scanner scanner = new Scanner(System.in); //you only need one

int userInput = 0;
int guesses = 0;
int min = 1;
int max = 100;
int range = max - min + 1;
int randNum = (int)(Math.random() * range) + min;
boolean valid = false;
boolean playAgain = false;

do {
  System.out.println("\nThis program is a guessing game.");
  System.out.println("\nThe computer will pick a random number between 1 and 100.");
  System.out.println("\nYou will try to guess it.");
  System.out.println("\nLet's play!");

  do {
    System.out.println("\nI'm thinking of a number between 1 and 100.");
    do {
      System.out.println("Please enter your guess: ");
      if (scanner.hasNextInt()){
        userInput = scanner.nextInt();
        valid = true;
      }
      else {
        System.out.println("Error: Please enter a whole number.\n");
        scanner.nextLine();
        userInput = -1; //this is important
        valid = false;
      }
    } while(!valid);

    if (userInput == randNum) {
      System.out.println("You got it!");
      System.out.println("It took you " + guesses + " tries");
      valid = true;
    }
    else {
      valid = false; //this is important
      ++guesses;
      if (userInput > randNum) {
        System.out.println("\nToo high!");
      }
      else {
        System.out.println("\nToo Low!");
      }
    }
  } while(!valid);

  do {
    System.out.println("\nDo you want to play again?");
    System.out.println("\nEnter 'Y' if yes and 'N' if no.");
    String play = scanner.nextLine();

    if (play.equalsIgnoreCase("Y")) {
      valid = true;
      playAgain = true;
    }
    else if (play.equalsIgnoreCase("N")) {
      valid = true;
      playAgain= false;
    }
    else {
      valid = false;
      System.out.println("Error: Please answer with 'Y' or 'N'");
    }
  } while(!valid);
} while(playAgain);

scanner.close();

但是,我建議使用更多函數(特別是對於內部 for 循環)來保持您的代碼可管理性和更易於理解。

暫無
暫無

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

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