【问题标题】:Program ignoring "If Else" and printing everything程序忽略“If Else”并打印所有内容
【发布时间】:2016-08-29 10:01:28
【问题描述】:

我正在尝试创建一个随机数生成器程序来跟踪玩家的赢、输、赢百分比和总赢利。该程序的逻辑是玩家在每个会话中获得 3 次机会,并且计算机生成一个随机数,玩家需要猜测或更确切地说应该匹配。

我尝试使用 if & else 语句来告诉用户他是否需要在 3 个允许的猜测范围内猜测更高或更低的数字。发生的情况是它完全忽略了条件并一次打印所有三个机会并结束游戏。

对此的任何意见将不胜感激。

游戏类:

import java.util.Scanner;

public class Game {

    Player player;
    LuckyNumberGenerator lng;

    public Game() {
        player = new Player();
        lng = new LuckyNumberGenerator();
    }

    public void eventLoop() {
        Scanner scanner = new Scanner(System.in);
        int choice = 0;
        boolean exit = false;
        while (!exit) {
            System.out.println("Welcome to the Guessing Game");
            System.out.println("==============================");
            System.out.println("(1) Set Up New Player");
            System.out.println("(2) Play One Round");
            System.out.println("(3) Player Win Statistics");
            System.out.println("(4) Display Game Help");
            System.out.println("(5) Exit Game");
            System.out.println("Choose an option: ");

            try {
                choice = Integer.parseInt(scanner.nextLine());
                if (choice < 1 || choice > 5) {
                    System.err.println("Error : Choose an option between 1 and 5");
                    choice = 0;
                }
            } catch (NumberFormatException e) {
                System.err.println("Error : Choose an option between 1 and 5");
                choice = 0;
            }

            switch (choice) {
                case 1:
                    createNewPlayer(scanner);
                    break;
                case 2:
                    guessNumber(scanner);
                    break;
                case 3:
                    printStatistics();
                    break;
                case 4:
                    printHelp();
                    break;
                case 5:
                    exit = true;
            }
        }
        scanner.close();
    }

    public void printHelp() {
        System.out.println(" ");
    }

    public void printStatistics() {
        try {
            if (player.getName() == null || player.getName().trim().length() < 1) {
                System.out.println("Player has not been set up!");
            } else {
                System.out.println("Player statistics are: ");
                System.out.println("Name: " + player.getName());
                System.out.println("Wins: " + player.getGamesWon());
                System.out.println("Losses: " + player.getGamesLost());
                System.out.println("Amount won so far: " + player.getTotalWinnings());
                System.out.println("Winnings percentage : "
                        + (((player.getGamesWon()) / (player.getGamesWon() + player.getGamesLost())) * 100));
            }
        } catch (ArithmeticException ae) {
            System.out.println("wins and loss both are 0: divide by zero exception");
        }
    }

    public void guessNumber(Scanner scanner) {
        int compGuess = lng.generate();
        int userGuess = 0;
        int numAttempts = 0;
        int cnum = lng.generateConsole();
        do {
            try {
                System.out.println("Guess a number between 1-100: ");
                userGuess = Integer.parseInt(scanner.nextLine());
                if (userGuess < 1 || userGuess > 100) {
                    System.err.println("Error : your Guess must be between 1-100");
                }
            } catch (Exception e) {
                System.err.println("Error : your Guess must be between 1-100");
            }
        } while (userGuess < 1 && userGuess > 100);
        do {
            if (userGuess > compGuess) {
                System.out.println("Your Guess is: " + userGuess + "and the random number: " + compGuess);
                System.out.println("Sorry, you need to go LOWER  :");
            } else if (userGuess < compGuess) {
                System.out.println("Your Guess is: " + userGuess + "and the random number: " + compGuess);
                System.out.println("Sorry, you need to go HIGHER  :");
            }
            numAttempts++;

            if (userGuess == compGuess) {
                System.out.println("Lucky Number was : " + compGuess + "your  guess was : " + userGuess);
                System.out.println("Congratulations you won " + 10 + "$");
                player.setGamesWon(1);
                player.setTotalWinnings(10);
            }

            if (userGuess != compGuess && (userGuess <= (compGuess + 5)) && (userGuess >= (compGuess - 5))) {
                System.out.println("Lucky Number was : " + compGuess + "your FINAL guess was : " + userGuess);
                System.out.println("Congratulations you won " + cnum + "$");
                player.setTotalWinnings(5);
            } else if (userGuess != compGuess) {
                System.out.println("Lucky Number was : " + compGuess + "your  guess was : " + userGuess);
                System.out.println("Sorry better Luck Next time");
                player.setGamesLost(1);
                player.setTotalWinnings(-1);
            }
        } while (userGuess != compGuess && numAttempts < 3);
    }

    public void createNewPlayer(Scanner scanner) {
        String name = null;
        do {
            try {
                System.out.println("Enter the name of the player: ");
                name = scanner.nextLine();
                if (name.isEmpty()) {
                    System.err.println("Name cannot be empty");
                }
            } catch (Exception e) {}
        } while (name.isEmpty());
        this.player = new Player(name);
    }

    public static void main() {
        Game game = new Game();
        game.eventLoop();
    }

}

【问题讨论】:

  • 我非常怀疑它是否忽略了else if 并且这是一个逻辑缺陷;)另外,格式化您的代码会使其更易于阅读。
  • 感谢您的意见凯文。这确实是一个逻辑缺陷,但并没有完全说明我哪里出错了。我是 Java 新手,这是我的第一个程序。我尝试了几种可能性,但似乎没有用。任何想法都会很棒。抱歉格式错误。

标签: java bluej


【解决方案1】:
do {
        try {
            System.out.println("Guess a number between 1-100: ");
            userGuess = Integer.parseInt(scanner.nextLine());
            if (userGuess < 1 || userGuess > 100) {
                System.err.println("Error : your Guess must be between 1-100");
            }
        } catch (Exception e) {
            System.err.println("Error : your Guess must be between 1-100");
        } 
    } while(userGuess < 1 && userGuess > 100);//incorrect

//correct condition -> while(userGuess < 1 || userGuess > 100); 

一个数字不能同时小于 1 和大于 100。

编辑 1:在您的第二个循环中,以下两个条件

1) if (userGuess != compGuess && (userGuess <= (compGuess + 5))
            && (userGuess >= (compGuess - 5))) 

2)else if (userGuess != compGuess)

只有当玩家的猜测次数超过尝试次数时才应该评估,因此两个 if 条件应该写在循环之外。

您还需要第一个 while 循环来保持用户输入在 1-100 之间有效,并且您的第二个 while 循环将在其中。

最终的代码将如下所示。

    do {

        do {
            try {
                System.out.println("Guess a number between 1-100: ");
                userGuess = Integer.parseInt(sc.nextLine());
                if (userGuess < 1 || userGuess > 100) {
                    System.err
                            .println("Error : your Guess must be between 1-100");
                }
            } catch (Exception e) {
                System.err
                        .println("Error : your Guess must be between 1-100");
            }
        } while (userGuess < 1 || userGuess > 100);

        System.out.println(" " + userGuess);

        if (userGuess > compGuess) {
            System.out.println("Your Guess is: " + userGuess
                    + "and the random number: " + compGuess);
            System.out.println("Sorry, you need to go LOWER  :");

        }
        if (userGuess < compGuess) {
            System.out.println("Your Guess is: " + userGuess
                    + "and the random number: " + compGuess);
            System.out.println("Sorry, you need to go HIGHER  :");
            System.out.println("if 1");
        }
        numAttempts++;

        if (userGuess == compGuess) {
            System.out.println("Lucky Number was : " + compGuess
                    + "your  guess was : " + userGuess);
            System.out.println("Congratulations you won " + 10 + "$");
            // player.setGamesWon(1);
            // player.setTotalWinnings(10);

        }

    } while (userGuess != compGuess & numAttempts < 3);

    if (userGuess != compGuess && (userGuess <= (compGuess + 5))
            || (userGuess >= (compGuess - 5))) {
        System.out.println("Lucky Number was : " + compGuess
                + " your FINAL guess was : " + userGuess);
        // System.out.println("Congratulations you won " + cnum + "$");
        // player.setTotalWinnings(5);

    } else if (userGuess != compGuess) {
        System.out.println("Lucky Number was : " + compGuess
                + "your  guess was : " + userGuess);
        System.out.println("Sorry better Luck Next time");
        // player.setGamesLost(1);
        // player.setTotalWinnings(-1);

    }

}

【讨论】:

  • 谢谢。我完全删除了条件。问题在于第二个 do while 循环。
  • 修改答案 1 秒
  • @ArvindSuryanarayana 如果对您有帮助,请查看我的回答。
  • 感谢您的详细解释。像魅力一样工作!
【解决方案2】:

尝试将第一个 do-while 放在第二个 do-while 的顶部。

【讨论】:

  • 试过了,但仍然是同样的问题。它会在第一次猜测后打印出所有内容。
  • 你能发布输出吗?你的意见
  • 选择选项 2 > 输入 4 > 得出:“你的猜测是 4,随机数是 48” > “你需要走得更高” > “幸运数字是 48,你的猜测是 4 " > "对不起,下次好运"。
  • 尝试将 numAttempts++ 放在前两个 ifs/if else 中,并将所有其他 ifs 更改为 if else。
  • 那是因为您已经使用 if (userGuess > compGuess) 和 if (userGuess compGuess) 和 if (userGuess compGuess && numAttempts
【解决方案3】:
while(userGuess < 1 && userGuess > 100);
        do{

这包含错误。循环应该在 userGuess 介于 1 到 100 之间时运行,您已将其排除在外。

应该是

while(userGuess >= 1 && userGuess <= 100);
        do{

【讨论】:

  • 谢谢。但这仅适用于第一个循环,并且运行良好。这是我遇到的第二个问题。
  • 请原谅我懒得尝试自己,但是即使它有一个分号也可以吗?
  • 啊,没关系。 while 与它下面的 do 完全无关。
【解决方案4】:

AND 条件需要更改为 OR 条件。因为您只想在用户输入低于 1 或高于 100 的内容时循环。

while(userGuess < 1 && userGuess > 100);  ===> while(userGuess < 1 || userGuess > 100);

同样,需要将另一个 AND 更改为 OR

// Issue with logic
if (userGuess != compGuess && (userGuess <= (compGuess + 5)) &&
               (userGuess >= (compGuess - 5))) {

// Corrected Code
if (userGuess != compGuess && (userGuess <= (compGuess + 5)) ||
               (userGuess >= (compGuess - 5))) {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    • 2022-11-28
    • 1970-01-01
    相关资源
    最近更新 更多