質問

I wrote a poker program that deals out cards to an inputted number of players and then deals the house cards. I'm wondering how to ask at the end if the player wants to play again and put the program into a loop. So that if they enter "Yes" then the program restarts but if they enter "No" then the program ends. How should I do this?

import java.io.*;

public class Dealer {

    public static void main(String[] args) throws IOException {

        BufferedReader in;
        int x;
        String playerx;

        in = new BufferedReader(new InputStreamReader(System.in));
        System.out
                .println("Welcome to the Casino! My name is Zack and I'm going to be dealing your table. How many players are playing?");
        playerx = in.readLine(); // user input for menu selection
        x = Integer.valueOf(playerx).intValue();

        while (x >= 1 && x <= 24) {

            // create a deck of 52 cards and suit and rank sets
            String[] suit = { "Clubs", "Diamonds", "Hearts", "Spades" };
            String[] rank = { "2", "3", "4", "5", "6", "7", "8", "9", "10",
                    "Jack", "Queen", "King", "Ace" };

            // initialize variables
            int suits = suit.length;
            int ranks = rank.length;
            int n = suits * ranks;
            // counter (5 house cards and 2 cards per player entered)
            int m = 5 + (x * 2);

            // initialize deck
            String[] deck = new String[n];
            for (int i = 0; i < ranks; i++) {
                for (int j = 0; j < suits; j++) {
                    deck[suits * i + j] = rank[i] + " of " + suit[j];

                }
            }

            // create random 5 cards
            for (int i = 0; i < m; i++) {
                int r = i + (int) (Math.random() * (n - i));
                String t = deck[r];
                deck[r] = deck[i];
                deck[i] = t;
            }

            // print results
            for (int i = 0; i < m; i++) {
                System.out.println(deck[i]);
            }
        }
    }
}
役に立ちましたか?

解決

Kill 2 birds with one stone: Give the person running the program the ability to exit before any hands are dealt, in case they do not wish to play. You already have the structure in place.

while(1) {
    System.out.println("Welcome to ... How many players are playing (1-24) or enter 0 to exit?");
    x = Integer.valueOf(playerx).intValue();
    if(x == 0 || x >= 24) {
        break;
    }
    // rest of your logic remains.....
}

他のヒント

I assume you've had no previous experience in programming before? I would suggest you read the sun docs found here. Before you think about adding an option to play again, learn about variables, methods, objects and constructors. Youtube tutorials can also help you if you're a beginner, but don't just rely on them.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top