mardi 21 novembre 2017

Why is this if statement being skipped with String variables? (Java) [duplicate]

This question already has an answer here:

I'm working on a blackjack game, and I'm currently trying to add gambling and allow players to play the game again. However, when I try to let the user leave the game, the game keeps playing itself over again, not letting the user leave. The blackjack game itself is in another method, and I call it in this method with "blackjack.game()".

    import java.util.Scanner;
public class Gambling{

public static void main(String args[]){

    //Scanner in = new Scanner(System.in);
    String again = "J";
    int chips = 500;
    int bet;
    boolean win;

    Blackjack blackjack = new Blackjack();

    System.out.println("House Rules: " +
            "\n1. Dealer draws to 17" +
            "\n2. Ties go to the dealer" +
            "\n3. Ace is always low" +
            "\n4. Drawing 21 is always a Blackjack" +
            "\n5. Dealer draws only one card until after user stays or folds" +
            "\n");

    blackjack.game();

    while (again != "N"){

        Scanner in = new Scanner(System.in);

        System.out.println("Play again? [Y] / [N]");
        again = in.next().toUpperCase();

        if(again == "N"){
            System.out.println("\nYou ended with " + chips + " chips");
            System.exit(0);

        }//end if

        if(again != "N"){
            System.out.println("You have " + chips + " chips.\nEnter your bet: ");
            bet = in.nextInt();

            while (bet > chips){
                System.out.println("You don't have enough chips for that bet. Enter a new amount: ");
                bet = in.nextInt();

            }//end while

            win = blackjack.game();
            if (win == true){
                chips += bet;
                System.out.println("\nYou won " + bet + " chips");
            }else if (win == false){
                chips -= bet;
                System.out.println("\nYou lost " + bet + " chips");

            }//end if

        }//end if

        if (chips <= 0){
            System.out.println("You've gone broke.");
            System.exit(0);

        }//end if

    }//end while

}//end main

}//end Gambling

The problem occurs around the "if (again == )" parts, and I've tried changing the variables and how it checks itself against them. I've yet again to check if it is not equal to Y if it is equal to N, not equal to N, and equal to Y. I'm confused because I think this should be working, but it doesn't seem to be. Is there something that I missed or a flaw in my logic? When the user types an "N" it should let them leave, but it just doesn't.

Aucun commentaire:

Enregistrer un commentaire