简体   繁体   English

程序忽略“ If else”并打印所有内容

[英]Program ignoring “If Else” and printing everything

I'm trying to create a Random Number Generator program which tracks a player's wins, losses, winning percentage and total winnings. 我正在尝试创建一个随机数生成器程序,该程序可跟踪玩家的获胜,失败,获胜百分比和总奖金。 The logic of the program is that a player gets 3 chances per session and the computer generates a random number which the player needs to guess or rather should match. 该程序的逻辑是,玩家每次会话获得3次机会,并且计算机生成一个随机数,玩家需要猜测或应该匹配该随机数。

I've tried to use if & else statements to tell the user if he needs to guess a higher number or a lower number within the 3 allowed guesses. 我尝试使用if&else语句来告诉用户他是否需要猜测3个允许的猜测中的较高数字或较低数字。 What's happening is that it completely ignores the conditions and prints all three chances at once and ends the game. 发生的情况是它完全忽略了条件并立即打印出所有三个机会并结束了游戏。

Any inputs on this would be highly appreciated. 任何对此的投入将不胜感激。

Game Class: 游戏类别:

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

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

a number cannot be less than 1 and greater than 100 at the same time. 一个数字不能同时小于1和大于100。

Edit 1 : In your 2nd loop the following two condition 编辑1:在第二个循环中,以下两个条件

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

2)else if (userGuess != compGuess)

should only be evaluated if the number of guesses by player exceeds the number of attempts, therefore the two if conditions should be written outside the loop. 仅当玩家猜出的次数超过尝试次数时才应评估,因此应将两个if条件写入循环之外。

Also you need the first while loop to keep the user input valid between 1-100, And your second while loop will be inside it. 另外,您还需要第一个while循环以使用户输入在1到100之间有效,而第二个while循环将在其中。

The final code will look something like this. 最终代码将如下所示。

    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放在第二个do-while的顶部。

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

This contains the error. 这包含错误。 The loop should run while the userGuess is between 1 and 100, you have excluded it. 当userGuess在1到100之间时,循环应该运行,您已经排除了它。

It should be 它应该是

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

AND condition needs to be changed to an OR condition. AND条件需要更改为OR条件。 Because you want to loop only when the user inputs something lower than 1 or higher than 100. 因为您只想在用户输入的数字小于1或大于100时循环。

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

Again, another AND needs to be changed to OR . 同样,另一个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))) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM