How do I make a space be accepted in the input

So I made a Blackjack game and it work fine but I found this error when I was testing. If someone input their name with a space the game breaks and errors. So how can I fix that. I have tried next() abd nextLine() didn’t work. Down below is my code the Blood part is where the fix should happen. But I am not sure how to fix it.

The Game:

BLACKJACK RULES:
-Each player is dealt 2 cards. The dealer is dealt 2 cards with one face-up and one face-down.
-Cards are equal to their value with face cards being 10 and an Ace being 1 or 11.
-The players cards are added up for their total.
-Players Hit to gain another card from the deck. Players Stay to keep their current card total.
-Dealer Hits until they equal or exceed 17.
-The goal is to have a higher card total than the dealer without going over 21.
-If the player total equals the dealer total, it is a Push and the hand ends.
-Players win their bet if they beat the dealer. Players win 1.5x their bet if they get Blackjack which is 21.
-Note that: (C) Clubs (?), (D) Diamonds (?), (H) Hearts (?), (S) Spades (?), (J) Jack (?,?,?,?), (Q) Queen (?,?,?,?) and (K) King (?,?,?,?).

How many people are playing (1-6)? 1
What is player 1’s name? sa mi <<< this where it crashes
How much do you want to bet sa, you got (1-100) J Coins?

My Code:

import java.util.Scanner;

public class BlackjackGame {

private Scanner input = new Scanner(System.in);
private int users;
private Player[] players;
private Deck deck;
private Dealer dealer = new Dealer();

// Starts game and displays the rules
public void initializeGame() {
    String names;
    System.out.println("Welcome to Blackjack!");
    System.out.println("");
    System.out.println("  BLACKJACK RULES: ");
    System.out.println(
            "    -Each player is dealt 2 cards. The dealer is dealt 2 cards with one face-up and one face-down.");
    System.out.println("    -Cards are equal to their value with face cards being 10 and an Ace being 1 or 11.");
    System.out.println("    -The players cards are added up for their total.");
    System.out.println(
            "    -Players Hit to gain another card from the deck. Players Stay to keep their current card total.");
    System.out.println("    -Dealer Hits until they equal or exceed 17.");
    System.out.println("    -The goal is to have a higher card total than the dealer without going over 21.");
    System.out.println("    -If the player total equals the dealer total, it is a Push and the hand ends.");
    System.out.println(
            "    -Players win their bet if they beat the dealer. Players win 1.5x their bet if they get Blackjack which is 21.");
    System.out.println(
            "        -Note that: (C) Clubs (♣), (D) Diamonds (♦), (H) Hearts (♥), (S) Spades (♠), (J) Jack (♣,♦,♥,♠), (Q) Queen (♣,♦,♥,♠) and (K) King (♣,♦,♥,♠).");
    System.out.println("");
    System.out.println("");

    // Gets the amount of players and creates them. Check that only up to 6 players
    // can play.
    do {
        System.out.print("How many people are playing (1-6)? "); // The Game can be played with 1-6 player.
        users = input.nextInt();
        if (users >= 7) { // there can only be 6 players anything higher re-ask how many player.
            System.out.println("Invalid entry. There can't be this much player's. Up to 1-6 player only.");
        }

    } while (users > 6 || users < 0);

    players = new Player[users];
    deck = new Deck();

   ** // Asks for player names and assigns them
    for (int i = 0; i < users; i++) {
        System.out.print("What is player " + (i + 1) + "'s name? ");
        names = input.next();
        players[i] = new Player();
        players[i].setName(names);
    }**
}

// Shuffles the deck
public void shuffle() throws InvalidDeckPositionException, InvalidCardSuitException, InvalidCardValueException,
        InvalidSpaceException {
    deck.shuffle();

}

// Gets the bets from the players
public void getBets() {
    int betValue;

    for (int i = 0; i < users; i++) {
        if (players[i].getBank() > 0) {
            do {
                System.out.print("How much do you want to bet " + players[i].getName() + ", you got"
                        + (" (1-" + players[i].getBank()) + ") " + "J Coins? ");
                betValue = input.nextInt();
                players[i].setBet(betValue);
            } while (!(betValue > 0 && betValue <= players[i].getBank()));
            System.out.println("");
        }

    }

}

// Deals the cards to the players and dealer
public void dealCards() {
    for (int j = 0; j < 2; j++) {
        for (int i = 0; i < users; i++) {
            if (players[i].getBank() > 0) {
                players[i].addCard(deck.nextCard());
            }
        }

        dealer.addCard(deck.nextCard());
    }
}

// Initial check for dealer or player Blackjack
public void checkBlackjack() {
    // System.out.println();

    if (dealer.isBlackjack()) {
        System.out.println("Dealer has BlackJack!");
        for (int i = 0; i < users; i++) {
            if (players[i].getTotal() == 21) {
                System.out.println(players[i].getName() + " pushes");
                players[i].push();
            } else {
                System.out.println(players[i].getName() + " loses");
                players[i].bust();
            }
        }
    } else {
        if (dealer.peek()) {
            System.out.println("Dealer peeks and does not have a BlackJack");
        }

        for (int i = 0; i < users; i++) {
            if (players[i].getTotal() == 21) {
                System.out.println(players[i].getName() + " has blackjack!");
                players[i].blackjack();
            }
        }
    }
}

// This code takes the user commands to hit or stand
public void hitOrStand() {
    String command;
    char c;
    for (int i = 0; i < users; i++) {
        if (players[i].getBet() > 0) {
            System.out.println();
            System.out.println(players[i].getName() + " has " + players[i].getHandString());

            do {
                do {
                    System.out.print(players[i].getName() + " (H)it or (S)tand? ");
                    command = input.next();
                    c = command.toUpperCase().charAt(0);
                } while (!(c == 'H' || c == 'S'));
                if (c == 'H') {
                    players[i].addCard(deck.nextCard());
                    System.out.println(players[i].getName() + " has " + players[i].getHandString());
                }
            } while (c != 'S' && players[i].getTotal() <= 21);
        }
    }
}

// Code for the dealer to play
public void dealerPlays() {
    boolean isSomePlayerStillInTheGame = false;
    for (int i = 0; i < users && isSomePlayerStillInTheGame == false; i++) {
        if (players[i].getBet() > 0 && players[i].getTotal() <= 21) {
            isSomePlayerStillInTheGame = true;
        }
    }
    if (isSomePlayerStillInTheGame) {
        dealer.dealerPlay(deck);
    }
}

// This code calculates all possible outcomes and adds or removes the player
// bets
public void settleBets() {
    System.out.println();

    for (int i = 0; i < users; i++) {
        if (players[i].getBet() > 0) {
            if (players[i].getTotal() > 21) {
                System.out.println(players[i].getName() + " has busted");
                players[i].bust();
            } else if (players[i].getTotal() == dealer.calculateTotal()) {
                System.out.println(players[i].getName() + " has pushed");
                players[i].push();
            } else if (players[i].getTotal() < dealer.calculateTotal() && dealer.calculateTotal() <= 21) {
                System.out.println(players[i].getName() + " has lost");
                players[i].loss();
            } else if (players[i].getTotal() == 21) {
                System.out.println(players[i].getName() + " has won with blackjack!");
                players[i].blackjack();
            } else {
                System.out.println(players[i].getName() + " has won");
                players[i].win();

            }
        }
    }

}

// This prints the players hands
public void printStatus() {
    for (int i = 0; i < users; i++) {
        if (players[i].getBank() > 0) {
            System.out.println(players[i].getName() + " has " + players[i].getHandString());
        }
    }
    System.out.println("Dealer has " + dealer.getHandString(true, true));
}

// This prints the players banks and tells the player if s/he is out of the game
public void printMoney() {
    for (int i = 0; i < users; i++) {
        if (players[i].getBank() > 0) {
            System.out.println(players[i].getName() + " has " + players[i].getBank() + " J Coins ");
        }
        if (players[i].getBank() == 0) {
            System.out.println(players[i].getName() + " has " + players[i].getBank() + " J Coins "
                    + " and is out of the game.");
            players[i].removeFromGame();
        }
    }
}

// This code resets all hands
public void clearHands() {
    for (int i = 0; i < users; i++) {
        players[i].clearHand();
    }
    dealer.clearHand();

}

// This decides to force the game to end when all players lose or lets players
// choose to keep playing or not
public boolean playAgain() {
    String command;
    char c;
    Boolean playState = true;
    if (forceEnd()) {
        playState = false;
    } else {
        do {
            System.out.println("");
            System.out.print("Do you want to play again (Y)es or (N)o? ");
            command = input.next();
            c = command.toUpperCase().charAt(0);
        } while (!(c == 'Y' || c == 'N'));
        if (c == 'N') {
            playState = false;
        }
    }
    return playState;
}

// This says true or false to forcing the game to end
public boolean forceEnd() {
    boolean end = false;
    int endCount = 0;

    for (int i = 0; i < users; i++) {
        if (players[i].getBank() == -1) {
            endCount++;
        }
    }
    if (endCount == users) {
        end = true;
    }
    if (end) {
        System.out.println("");
        System.out.println("All players have lost and the game ends.");
    }

    return end;
}

// This is the endgame code for when all players are out of the game or players
// decide to stop playing
public void endGame() {
    int endAmount;
    String endState = " no change.";
    System.out.println("");
    for (int i = 0; i < users; i++) {
        if (players[i].getBank() == -1) {
            players[i].resetBank();
        }
        endAmount = players[i].getBank() - 100;
        if (endAmount > 0) {
            endState = " gain of ";
        } else if (endAmount < 0) {
            endState = " loss of ";
        }
        System.out.println(players[i].getName() + " has ended the game with " + players[i].getBank() + ".");
        if (endState != " no change.") {
            System.out.println("A" + endState + Math.abs(endAmount) + ".");
        } else {
            System.out.println("No change from their starting value.");
        }
        System.out.println("");
    }
    System.out.println("");
    System.out.println("");
    System.out.println("Thank you for playing!");
}

} // End class

I have tried next() abd nextLine() didn’t work.

Doing nextLine() broke the code even more when I run it and play the game.

>Solution :

The problem here is that input.next() only reads the input until the space. So if you give input as "sa mi", it only reads "sa" and "mi" is left in the input stream. When it tries to read the next integer (for example, while taking input for "How many people are playing (1-6)? "), it finds a string ("mi") instead of an integer and throws an error.

One way to solve this problem is to use input.nextLine() which reads input until the end of line (\n). After reading each line, you can then trim the input to remove leading and trailing whitespaces. Here is how you can change your code:

`// Asks for player names and assigns them
 for (int i = 0; i < users; i++) {
     System.out.print("What is player " + (i + 1) + "'s name? ");
     names = input.nextLine().trim();
     players[i] = new Player();
     players[i].setName(names);
 }`

However, you mentioned that using nextLine() broke the code even more. This is because of a common issue with Scanner where nextInt() and nextLine() behave a little differently. nextInt() only reads the number and not the end of line (\n). So when you subsequently call nextLine(), it reads the leftover newline character from the previous input.

One way to handle this issue is by adding an extra nextLine() after nextInt(). So you can change this:

`users = input.nextInt();`

to:

`users = input.nextInt();
input.nextLine();  // consume leftover newline`

This will consume the leftover newline after reading the integer input, and should make the rest of the code work as expected.

Leave a Reply