当前位置: 代码迷 >> java >> Java - 继续游戏
  详细解决方案

Java - 继续游戏

热度:96   发布时间:2023-07-17 20:29:49.0

我制作了一些命令行游戏,在游戏结束时我想询问玩家是否想再玩一次。 你可以在代码中看到我是如何制作的,但它不起作用,我不知道为什么。

有谁能够帮助我?

import java.util.Scanner;
//WIP
public class GuessingGame2 {

    static Scanner userInput = new Scanner(System.in);

    static int randNumber;
    static int guessNumber;
    static boolean gameStatus;

    static void checkNum(int x) {


        guessNumber++;

        if(x == randNumber) {
            gameStatus = true;
        } else if(x < randNumber) {
            System.out.println("Too small!");
        } else {
            System.out.println("Too big!");
        }       
    }

    static void checkAnsw() {

        if(userInput.hasNextLine()) {

            if(userInput.nextLine() == "Y" || userInput.nextLine() == "y") {
                guessGame();
            } else if(userInput.nextLine() == "N" || userInput.nextLine() == "n") {

            } else {
                System.out.print("Y or N ");
                checkAnsw();
            }

        } else {
            System.out.print("Y or N ");
            userInput.next();
            checkAnsw();
        }
    }

    static void guessGame() {

        randNumber = (int) (Math.random() * 1000);
        guessNumber = 0;
        gameStatus = false;

        System.out.println("Try to guess a number from 1 to 1000!");

        while(gameStatus == false) {

            System.out.print("Your guess: ");

            if(userInput.hasNextInt()) {
                checkNum(userInput.nextInt());
            } else {
                System.out.println("You need to choose a number!");
                userInput.next();
            }
        }

        System.out.println("You guessed the number in " + guessNumber + "  tries.");
        System.out.print("Do you want to play again? Y or N ");

        checkAnsw();

    }

    public static void main(String[] args) {

        guessGame();

    }
}

checkAnsw方法更改为:

static void checkAnsw() {

if(userInput.hasNextLine()) {

    if(userInput.nextLine().equalsIgnoreCase("y")) {
        guessGame();
    } else if(userInput.nextLine().equalsIgnoreCase("n")) {

    } else {
        System.out.print("Y or N ");
        checkAnsw();
    }

    } else {
        System.out.print("Y or N ");
        userInput.next();
        checkAnsw();
    }
}

您无法将字符串与=进行比较,因为它们是对象。 使用.equals方法比较字符串。

你的代码工作正常,我已经在Eclipse中复制并粘贴它,这是输出:

Try to guess a number from 1 to 1000!
Your guess: eeeee
You need to choose a number!
Your guess: 1
Too small!
Your guess: 2
Too small!
Your guess: 2

我不明白你的问题是什么,试着更好地解释一下

  相关解决方案