Java - 继续游戏

时间:2015-07-25 16:23:33

标签: java loops

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

有人能帮助我吗?

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

    }
}

2 个答案:

答案 0 :(得分:3)

@echo %~dp0 方法更改为:

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(); } } 进行比较,因为它们是对象。使用=方法比较字符串。

答案 1 :(得分:0)

您的代码运行正常,我已将其复制并粘贴到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

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