I've made this poker program. It evaluates the hand and returns the results.
Everything works except my method to check for a straight. There is no error, but the method never returns true.
As a test, I have a while loop on the main (DeckOfCardsTest) to rerun the program until a straight is found.
Here is the code:
public class DeckOfCardsTest {
public static Card[] hand = new Card[5];
public static void main(String[] args) {
while(DeckOfCards.str == 0){
DeckOfCards myDeckOfCards = new DeckOfCards();
myDeckOfCards.shuffle(); // place Cards in random order
// print the hand dealt
for (int i = 0; i < 5; i++) {
// deal and display a Card
//System.out.printf("%-19s%n", myDeckOfCards.dealCard());
hand[i]= myDeckOfCards.dealCard();
if (i % 5 == 0) { // output a newline after every fifth card, incase dealing 2 hands in the future
System.out.println();
}
}//end of for loop
for(int i = 0; i < hand.length; i++){
System.out.println(""+ hand[i]);
}
DeckOfCards.Pair();//check hand for pair, 2 pair, 3 of a kind, four of a kind, or a full house
DeckOfCards.hasFlush(hand);//check hand for flush
System.out.println("\n\n\t" + DeckOfCards.Results() + "\n\n " + DeckOfCards.str);
//System.out.println(""+DeckOfCards.hasStraight(hand));
DeckOfCards.flushn=0;
}
} //end of main
}//end of class
Card Class
public class Card {
private final String face; // face of card ("Ace", "Deuce", ...)
private final String suit; // suit of card ("Hearts", "Diamonds", ...)
// two-argument constructor initializes card's face and suit
public Card(String cardFace, String cardSuit) {
this.face = cardFace; // initialize face of card
this.suit = cardSuit; // initialize suit of card
} //end of Card inilization
// return String representation of Card
public String toString() {
return face + " of " + suit;
}// endof toString method
public String getFace() {
return face;
}//end of getFace method
public String getSuit() {
return suit;
}//end of getSuit method
}//end of Class
Deck class
import java.security.SecureRandom;
public class DeckOfCards {
// random number generator
private static final SecureRandom randomNumbers = new SecureRandom();
private static final int NUMBER_OF_CARDS = 52; // constant # of Cards
public static int flushn = 0;
public static int str=0;
//private Card[] hand;
private Card[] deck = new Card[NUMBER_OF_CARDS]; // Card references
private int currentCard = 0; // index of next Card to be dealt (0-51)
// constructor fills deck of Cards
public DeckOfCards() {
String[] faces = {"Ace", "Deuce", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
String[] suits = {"Hearts", "Diamonds", "Clubs", "Spades"};
// populate deck with Card objects
for (int count = 0; count < deck.length; count++) {
deck[count] =
new Card(faces[count % 13], suits[count / 13]);
}
} //end of DeckOfCards constructor
public String getCard(){
String cCard = ("");
return cCard;
}
// shuffle deck of Cards with one-pass algorithm
public void shuffle() {
// next call to method dealCard should start at deck[0] again
currentCard = 0;
// for each Card, pick another random Card (0-51) and swap them
for (int first = 0; first < deck.length; first++) {
// select a random number between 0 and 51
int second = randomNumbers.nextInt(NUMBER_OF_CARDS);
// swap current Card with randomly selected Card
Card temp = deck[first];
deck[first] = deck[second];
deck[second] = temp;
}
} //end of shuffle method
// deal one Card
public Card dealCard() {
// determine whether Cards remain to be dealt
if (currentCard < deck.length) {
return deck[currentCard++]; // return current Card in array
}
else {
return null; // return null to indicate that all Cards were dealt
}
}//end of dealCard method
public static void hasFlush(Card[] hand) {
boolean isFlush = true;
String suit = hand[0].getSuit();
for(int i = 1; i < hand.length; i++) {
if(!(hand[i].getSuit().equals(suit))) {
isFlush = false;
}
}
if(isFlush){
flushn = 5;
}
}//end of flush evaluation
public static boolean hasStraight(Card[] hand) {
String[] faces = {"Ace", "Deuce", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
int minFace = 13;
for(int i = 0; i < hand.length; i++) {
int face = 13;
for(int j = 0; j < faces.length; j++) {
if(hand[i].getFace().equals(faces[j])) {
face = j;
}
}
if(face < minFace) {
minFace = face;
}
}
if(minFace > 7) {
return false;
}
boolean isStraight = true;
for(int i = minFace+1; i < minFace+hand.length; i++) {
boolean found = false;
for(int j = 0; j < hand.length; j++) {
if(hand[j].getFace().equals(faces[i])) {
found = true;
str++;
}
}
if(!found) {
str=0;
isStraight = false;
}
}
return isStraight;
}
public static int Pair(){
int pair = 0, done = 0, handcount = 1;
int pairCheck=0;
while (done <1){
for(int i = 0; i < 4; i++){
String tempCard = DeckOfCardsTest.hand[i].getFace();
for(int j=handcount; j < DeckOfCardsTest.hand.length; j++){
if(tempCard.equals(DeckOfCardsTest.hand[j].getFace()))
pair++;
}
handcount++;
}
pairCheck = pair;
done++;
}
return pairCheck;
}//endof Pair method
public static String Results(){
String results=("High Card");
int checkHand = 0;
if (Pair()>0 ){
switch (Pair()){
case 1:
results = ("Pair");
break;
case 2:
results = ("Two Pair!");
break;
case 3:
results = ("Three of a kind!");
break;
case 4:
results = ("Full House!");
break;
case 6:
results = ("FOUR of a kind!");
break;
default:
results = ("Somthing went terribly wrong, sorry");
break;
}
}//end of pairing results
if (flushn > 0){
results = ("Flush!");
}
if (str > 0){
results = ("Straight!");
}
return results;
}
}//end of Class
There is no error, but the method never returns true
This is not true. Your current hasStraight method is almost correct and does in fact return true/false correctly. The main issue you have is that your main loop uses the static variable str. There is a bug which does not reset str to zero correctly.
In short, there are two ways to address your problem:
1) Fix the issue with str
if (!found) {
str = 0;
isStraight = false;
break;
}
2) The main loop should use the boolean result of hasStraight instead of str.
boolean b = false;
while (!b) {
DeckOfCards myDeckOfCards = new DeckOfCards();
myDeckOfCards.shuffle(); // place Cards in random order
// print the hand dealt
for (int i = 0; i < 5; i++) {
// deal and display a Card
// System.out.printf("%-19s%n", myDeckOfCards.dealCard());
hand[i] = myDeckOfCards.dealCard();
if (i % 5 == 0) { // output a newline after every fifth card,
// incase dealing 2 hands in the future
System.out.println();
}
} // end of for loop
for (int i = 0; i < hand.length; i++) {
System.out.println("" + hand[i]);
}
DeckOfCards.Pair();// check hand for pair, 2 pair, 3 of a kind, four
// of a kind, or a full house
DeckOfCards.hasFlush(hand);// check hand for flush
System.out.println("\n\n\t" + DeckOfCards.Results() + "\n\n " + DeckOfCards.str);
b = DeckOfCards.hasStraight(hand);
System.out.println("Straight= " + b);
DeckOfCards.flushn = 0;
}
If I use either of these fixes, the main loop will loop until there is a straight.
Notes:
1. I believe the minFace check should be:
if (minFace > 8) {
return false;
}
Can an ace be high?
Ace code?
boolean hasAce = false;
for (int i = 0; i < hand.length; i++) {
if (hand[i].getFace().equals("Ace"))
hasAce = true;
}
// ... Current code ....
if (!isStraight && hasAce) {
isStraight = true;
for (int i = 9; i < 13; i++) {
boolean found = false;
for (int j = 0; j < hand.length; j++) {
if (hand[j].getFace().equals(faces[i])) {
found = true;
str++;
}
}
if (!found) {
str = 0;
isStraight = false;
break;
}
}
}
return isStraight;
Related
I am working on the tortoise and hare game, and everything works except I want to print out "OUCH" when the hare and the tortoise are in the same position. My race track is a character array so I can only put 'O', and whenever I try to print it as a string "OUCH" it prints it as a separate new line. Is there a way to print "OUCH" without breaking up the flow of the game, and outputting it on a different line to everything else?
public static int turtlePosition = 0; // Turtle location
public static int harePosition = 0; // Hare location
public static char[] track = new char [70]; // Array for Track
public static void main(String[] args) {
System.out.println("AND THEY ARE OFF!!");
while (!gameOver()){
for (int i = 0; i < track.length; i++){
track[i] = '-';
}
Random random = new Random();
int r = random.nextInt(10) + 1;
turtleMove(r);
hareMove(r);
if (gameOver()){
break;
}
track[turtlePosition] = 'T';
track[harePosition] = 'H';
if (turtlePosition == harePosition){
String str = String.valueOf(track[turtlePosition]);
str = "OUCH";
System.out.println(str);
}
for (int i = 0; i < track.length; i++)
{
System.out.print(track[i]);
}
System.out.println();
}
if (turtlePosition >= 70 && harePosition >= 70){
System.out.println("IT'S A TIE!!");
}
else if (turtlePosition >= 70){
System.out.println ("TORTOISE WINS!!");
}
else {
System.out.println ("HARE WINS!!");
}
i don't believe so but you could put a text area to the side.
like this:
Code changes:
if (turtlePosition>=6 || harePosition>=6){
turtlePosition = 7;
harePosition = 7;
}
track[turtlePosition] = 'T';
track[harePosition] = 'H';
if (turtlePosition == harePosition){
insertintotrack("OUCH |");
}else {
insertintotrack(" |");
}
New Function:
public static void insertintotrack(String in)
{
char[] info = in.toCharArray();
for (int i = 0; i < info.length; i++) {
track[i] = info[i];
}
}
I made up a quick poker game. It generates 5 random numbers and converts those numbers into actual cards values and symbols based on their value. However, I have problems when it comes to making the hand evaluation.
So far I only did the flush right as it's really easy but even then it's not perfect (it prints that the user has a flush 5 times... ) and I would really appreciate if someone could help me with the pair, two pair, three of a kind and straight. I could do the rest afterwards but I just need a heads-up on how to do those.
Thank you in advance for your help, here is the code :
package tests;
import java.util.*;
public class TESTS {
public static void main(String[] args) {
boolean[] pack = new boolean[52]; // Array to not generate the same number twice
int[] cards = new int[5]; //The 5 unique random numbers are stored in here.
String[] cardsvalues = new String[5]; // This will assign the card's value based on the random number's value
char[] cardssymbols = new char[5];//This will assign the card's symbol based on the random number's value
char symbols[] = {'♥', '♦', '♣', '♠'}; // possible symbols that the random number can take
String values[] = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"}; // possible values that the random number can take
Random give = new Random();
for (int i = 0; i < cards.length; i++) { // Gives 5 unique random numbers
do {
cards[i] = give.nextInt(52);
} while (pack[cards[i]]);
pack[cards[i]] = true;
System.out.println(cards[i]);
}
for (int i = 0; i < cards.length; i++) { // This converts the number to a card symbol based on the number's value
final int numOfSymbol = cards[i] / 13;
cardssymbols[i] = symbols[numOfSymbol];
}
for (int i = 0; i < cards.length; i++) { // This converts the number to an actual card value based on the number's value.
final int numOfValues = cards[i] % 13;
cardsvalues[i] = values[numOfValues];
}
for (int i = 0; i < cardssymbols.length; i++) { // Prints the actual cards once they are converted
System.out.print(cardssymbols[i]);
System.out.println(cardsvalues[i]);
}
for (int i = 0; i < cardsvalues.length; i++) { //Here is the problem, i have no idea on how to make the handevaluator ...
if (cardsvalues[i] == cardsvalues[i] + 1) {
System.out.println("PAIR !!!");
} else if (cardsvalues[i] == cardsvalues[i] + 1 && cardsvalues[i] == cardsvalues[i] + 2) {
System.out.println("TRIPS !!!");
} else if (cardssymbols[0] == cardssymbols[1] && cardssymbols[1] == cardssymbols[2] && cardssymbols[2] == cardssymbols[3] && cardssymbols[3] == cardssymbols[4]) {
System.out.println("FLUSHHH");
}
}
}
Hints:
To simplify testing for straights and sorting by highest card, it is easier to represent ranks by their indexes, and only translate them to the symbols for printing.
Using a Card object allows for clearer code.
The Java Collection framework has useful functions for shuffling, slicing and sorting.
My solution:
public class Test {
static final char[] suits = {'♥', '♦', '♣', '♠'};
static final String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
static class Card {
final int suit;
final int rank;
Card(int s, int r) {
suit = s;
rank = r;
}
#Override
public String toString() {
return suits[suit] + ranks[rank]; // or however you want the cards to be printed
}
}
public static void main(String[] args) {
List<Card> deck = new ArrayList<>();
for (int s = 0; s < suits.length; s++) {
for (int r = 0; r < ranks.length; r++) {
deck.add(new Card(s,r));
}
}
Collections.shuffle(deck);
List<Card> hand = deck.subList(0,5);
Collections.sort(hand, Comparator.comparing(c -> c.rank));
System.out.println("Your hand is: " + hand);
System.out.println(value(hand));
}
static String value(List<Card> hand) {
boolean straight = true;
boolean flush = true;
for (int i = 1; i < hand.size(); i++) {
straight &= hand.get(i - 1).rank + 1 == hand.get(i).rank;
flush &= hand.get(i - 1).suit == hand.get(i).suit;
}
if (straight && flush) {
return "Straight Flush from " + hand.get(4);
}
List<Run> runs = findRuns(hand);
runs.sort(Comparator.comparing(r -> -r.rank));
runs.sort(Comparator.comparing(r -> -r.length));
if (runs.get(0).length == 4) {
return "Four of a Kind: " + runs;
}
if (runs.get(0).length == 3 && runs.get(1).length == 2) {
return "Full House: " + runs;
}
if (straight) {
return "Straight from " + hand.get(4);
}
if (runs.get(0).length == 3) {
return "Three of a Kind: " + runs;
}
if (runs.get(1).length == 2) {
return "Two pair: " + runs;
}
if (runs.get(0).length == 2) {
return "Pair: " + runs;
}
return "High card: " + runs;
}
/** Represents {#code length} cards of rank {#code rank} */
static class Run {
int length;
int rank;
#Override
public String toString() {
return ranks[rank];
}
}
static List<Run> findRuns(List<Card> hand) {
List<Run> runs = new ArrayList<>();
Run run = null;
for (Card c : hand) {
if (run != null && run.rank == c.rank) {
run.length++;
} else {
run = new Run();
runs.add(run);
run.rank = c.rank;
run.length = 1;
}
}
return runs;
}
}
Example output:
Your hand is: [♣10, ♥J, ♦J, ♠K, ♥K]
Two pair: [K, J, 10]
I am doing a Lotto application in a jForm/GUI in Netbeans with 3 rows of 5 numbers, and I don't want duplicates to be allowed on each line. To have one number on line 1 and the same on line 3 is OK, but to have those numbers on the same line is not OK.
The only way I can think of doing it that I know will work is to hard code it, and preferably, I don't want that.
I have tried:
boolean dup = false;
for (int k = 0; k < num[0].length){ //loop through columns
for (i = 0; i < num.length-1; i++) {
for (int j = i; j < inArray.length; j++){
if (num[k][i] == num[k][j]){
dup = true;
break;
}
}
}
}
and this:
public static boolean hasDuplicates(int [][] num) {
for (int row = 0; row < num.length; row++) {
int curRow = num[row];
Set set = Sets.newHashSet(Arrays.asList(curRow));
if (set.size() < curRow.length) {
return true;
}
}
return false;
}
I have also looked at other coding extensively and I can't get one that works.
The exact thing I'm trying to do is:
Get user's input for three lines of Lotto via text field, check each line for duplicates, print to a jLabel if it's a duplicate or leave the jLabel blank and run the rest of the code if there's no duplicates.
The current code I have is:
private void playBtnActionPerformed(java.awt.event.ActionEvent evt) {
num[0][0] = Integer.parseInt(line00Tf.getText());
num[0][1] = Integer.parseInt(line01Tf.getText());
num[0][2] = Integer.parseInt(line02Tf.getText());
num[0][3] = Integer.parseInt(line03Tf.getText());
num[0][4] = Integer.parseInt(line04Tf.getText());
num[1][0] = Integer.parseInt(line10Tf.getText());
num[1][1] = Integer.parseInt(line11Tf.getText());
num[1][2] = Integer.parseInt(line12Tf.getText());
num[1][3] = Integer.parseInt(line13Tf.getText());
num[1][4] = Integer.parseInt(line14Tf.getText());
num[2][0] = Integer.parseInt(line20Tf.getText());
num[2][1] = Integer.parseInt(line21Tf.getText());
num[2][2] = Integer.parseInt(line22Tf.getText());
num[2][3] = Integer.parseInt(line23Tf.getText());
num[2][4] = Integer.parseInt(line24Tf.getText());
duplicateLbl.setText("");
LottoPhase1 p1 = new LottoPhase1();
p1.setNum(num);
p1.createSecret();
secret = p1.getSecret();
p1.computeCheckInput();
correctL1 = p1.getCorrectL1();
correctL2 = p1.getCorrectL2();
correctL3 = p1.getCorrectL3();
//prints secret to output
System.out.println("Phase 1 Main Secret: " + Arrays.toString(secret));
System.out.println();
displayResults0Lbl.setText(Integer.toString(secret[0]) + ", " + Integer.toString(secret[1]) + ", " + Integer.toString(secret[2]) + ", " + Integer.toString(secret[3]) + ", " + Integer.toString(secret[4]));
matched1NumLbl.setText(Integer.toString(correctL1));
matched2NumLbl.setText(Integer.toString(correctL2));
matched3NumLbl.setText(Integer.toString(correctL3));
}
public static boolean hasDuplicates(int[][] num)
{
boolean hasDuplicate = false;
// for each line in num
for(int[] line : num)
{
// for every number in the row
for(int i = 0; i < line.length && !hasDuplicate; i++)
{
// for every number in the row
for(int j = 0; j < line.length; j++)
{
// if we are not comparing the same number
if(i != j)
{
// check for equality
if(line[i] == line[j])
{
hasDuplicate = true; // we have found a duplicate
break; // no need to keep checking; break the loop and return
}
}
}
}
}
return hasDuplicate;
}
The second method has a couple of errors, for instance,
int curRow = num[row];
Should actually be:
int[] curRow = num[row];
Also, you appear to be using Sets, which probably comes from some library you're using (Guava, Google Common, etc.). Assuming you were not using any library, you could change your code to something similar to:
public static boolean hasDuplicates(int [][] num) {
for (int[] curRow : num) {
Set<Integer> set = new HashSet<>();
for (int n : curRow) {
if (!set.add(n)) {
return true;
}
}
}
return false;
}
If you're using Java 8, one way to remove the second for loop is by using a Stream:
public static boolean hasDuplicates(int [][] num) {
for (int[] curRow : num) {
Set<Integer> set = IntStream.of(curRow).boxed().collect(Collectors.toSet());
if (set.size() < curRow.length) {
return true;
}
}
return false;
}
Other alternatives to the Stream can be found in threads like these.
Testing with the following input produces what I think you would expect:
int[][] testA = {{0,1,2,3,4}, {0,1,2,3,4}, {0,1,2,3,4}}; //false
int[][] testB = {{0,1,2,3,4}, {0,2,2,3,4}, {0,1,2,3,4}}; //true
int[][] testC = {{0,1,2,3,4}, {0,1,2,3,4}, {0,4,3,3,4}}; //true
int[][] testD = {{0,1,2,3,4}, {5,6,7,8,9}, {10,11,12,13,14}}; //false
I'm trying to convert an ArrayList that contains "cards", or objects that store two numbers, a rank and a suit. Normally to get a single instance of the card, I use:
dealer.dealerhand.get(1).showstats();
Where showstats returns a string and is:
public String showstats()
{
String realsuit = "";
if(this.suit == 0)
{
realsuit = "Diamonds";
}
else if(this.suit == 1)
{
realsuit ="Hearts";
}
else if(this.suit == 2)
{
realsuit = "Clubs";
}
else if(this.suit == 3)
{
realsuit = "Spades";
}
String str = "My rank is: " + this.rank + " My Suit is: " + realsuit;
return str;
}
What I've tried so far is:
public String[] getStats()
{
String[] dealerstats = this.dealerhand.toArray(new String[this.dealerhand.size()]);
return dealerstats;
}
and
public String[] getStats()
{
String[] dealerstats = {""};
for(int i = 0; i < this.dealerhand.size(); i++)
{
dealerstats[i] = (dealerhand.get(i).showstats());
}
return dealerstats;
}
But they both don't work. The end goal would be a string array of the cards in the dealerhand ArrayList, that I will print out using JList. Thanks!
For this:
public String[] getStats() {
for(int i = 0; i < this.dealerhand.size(); i++) {
dealerstats[i] = (dealerhand.get(i).showstats());
}
return dealerstats;
}
make sure to initialize your String array, such as below:
public String[] getStats(Dealer dealer) { // Input a dealer
String[] dealerstats = new String[dealer.dealerhand.size()]; // Initialize String array
for(int i = 0; i < this.dealerhand.size(); i++) {
dealerstats[i] = dealerhand.get(i).showstats();
}
return dealerstats;
}
I am also assuming you have a Dealer object, as you seem to reference one in your question.
Your second attempt is almost correct. You created the array but without giving it the correct size. The String[] dealerstats size should be the size of the ArrayList dealerhand:
public String[] getStats()
{
String[] dealerstats = new String[ dealerhand.size() ];
for( int i = 0; i < dealerstats.length; ++i )
dealerstats[i] = dealerhand.get(i).showstats();
return dealerstats;
}
If you define a toString() method in your Card class you can print the ArrayList out without any conversion (Live Ideone Example here):
public class Card{
...
#Override public String toString(){
return "My rank is: " + this.rank + " My Suit is: " + this.suit;
}
}
Then you can just use:
List<Card> dealerCards = new ArrayList<Card>();
dealerCards.add(new Card(5, "Hearts"));
dealerCards.add(new Card(10, "Diamonds"));
System.out.println(dealerCards);
Output: ["My rank is: 5 My Suit is: Hearts", "My rank is: 10 My Suit is: Diamonds"]
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
So I'm building a version of Go Fish. I am done with all of the coding, but it won't run because in the Player class, I can't use a Card.rank parameter in methods. I understand that, but I still need to be able to input a rank somehow.
Look at my Card constructor and any instance of me trying to use a Player method where I need a rank input (Player.subSets and Player.searchHand). (I am also only showing one player's turn code to be concise.)
Program (main) class:
import java.util.*;
public class Program
{
public static void main(String args[])
{
String[] rank = {"two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "jack", "queen", "king", "ace"};
String[] suit = {"hearts", "diamonds", "spades", "clubs"};
Scanner scan = new Scanner(System.in);
String something = "yes", something2 = "yes", success = "yes"; //Use with while loops
String turn = "one";
String temp; //Use with setting names
String temp2, temp3; //For player being searched
Card temp4 = new Card(); //For player being searched
Card[] deck = new Card[52]; //Deck array
int playercount = 0;
Player one = new Player("temp");
Player two = new Player("temp");
Player three = new Player("temp");
Player four = new Player("temp");
//Start game
while (something.equalsIgnoreCase("yes"))
{
//Prepare game
Card.makeDeck(deck, rank, suit);
deck = Card.getDeck();
Card.shuffle(deck);
while (something2.equalsIgnoreCase("yes") || playercount < 2) //Add players to game
{
System.out.println("Would a(nother) player like to join?");
something2 = scan.nextLine();
System.out.println();
if (something2.equalsIgnoreCase("yes"))
{
if (playercount <= 4)
{
if (playercount == 0)
{
System.out.println("What is your name: ");
Player one1 = new Player(scan.nextLine());
one = one1;
playercount++;
System.out.println();
}
else if (playercount == 1)
{
System.out.println("What is your name: ");
Player two2 = new Player(scan.nextLine());
two = two2;
playercount++;
System.out.println();
}
else if (playercount == 2)
{
System.out.println("What is your name: ");
Player three3 = new Player(scan.nextLine());
three = three3;
playercount++;
System.out.println();
}
else if (playercount == 3)
{
System.out.println("What is your name: ");
Player four4 = new Player(scan.nextLine());
four = four4;
playercount++;
System.out.println();
}
else {System.out.println("Only four players are allowed.");
something2 = "no";}
}
}
else if (playercount < 2)
{
System.out.println("You need at least two players...");
System.out.println();
}
}
//Deal cards
if (playercount == 2)
{
for (int i = 1; i < 8; i++)
{
one.addCard(Card.draw(deck));
deck = Card.getDeck();
two.addCard(Card.draw(deck));
deck = Card.getDeck();
}
}
else if (playercount == 3)
{
for (int i = 1; i < 8; i++)
{
one.addCard(Card.draw(deck));
deck = Card.getDeck();
two.addCard(Card.draw(deck));
deck = Card.getDeck();
three.addCard(Card.draw(deck));
deck = Card.getDeck();
}
}
else
{
for (int i = 1; i < 6; i++)
{
one.addCard(Card.draw(deck));
deck = Card.getDeck();
two.addCard(Card.draw(deck));
deck = Card.getDeck();
three.addCard(Card.draw(deck));
deck = Card.getDeck();
four.addCard(Card.draw(deck));
deck = Card.getDeck();
}
}
//Take turns
while (something.equalsIgnoreCase("yes"));
{
success = "yes";
if (turn.equalsIgnoreCase("one") && something.equalsIgnoreCase("yes"))
{
System.out.println("Player one: " + one.getName() + "'s turn!");
System.out.println();
//Output hand
System.out.println("You have: " + Card.toString(one.getHand()));
System.out.println();
//Ask what who to search
System.out.println("Whose hand would you like to check?");
System.out.println("(Enter a player's name.)");
temp2 = scan.nextLine(); //Set player name to temp2
System.out.println();
//Ask what to search
while (success.equalsIgnoreCase("yes"))
{
System.out.println("Remember, you have: " + Card.toString(one.getHand()));
System.out.println();
System.out.println("Would you like to search for a two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, or ace?");
temp3 = scan.nextLine(); //Set desired rank to temp3
//Check player two
if (temp2.equalsIgnoreCase(two.getName()))
{
if (two.searchHand(two.getHand(), temp3) != null)
{
while (two.searchHand(two.getHand(), temp3) != null)
{
one.addCard(two.searchHand(two.getHand(), temp3));
two.subCard(two.searchHand(two.getHand(), temp3));
one.subSets(one.getHand(), temp3);
}
}
else if (two.searchHand(two.getHand(), temp3) == null)
{
System.out.println();
System.out.println("Go fish!");
System.out.println(one.getName() + " drew a card.");
System.out.println();
one.addCard(Card.draw(deck));
one.subSets(one.getHand(), temp3);
deck = Card.getDeck();
turn = "two";
success = "no";
something = one.checkWin();
if (something.equalsIgnoreCase("no"))
System.out.println(one.getName() + " won!");
}
}
//Check player three
if (temp2.equalsIgnoreCase(three.getName()))
{
if (three.searchHand(three.getHand(), temp3) != null)
{
while (three.searchHand(three.getHand(), temp3) != null)
{
one.addCard(three.searchHand(three.getHand(), temp3));
three.subCard(three.searchHand(three.getHand(), temp3));
one.subSets(one.getHand(), temp3);
}
}
else if (three.searchHand(three.getHand(), temp3) == null)
{
System.out.println();
System.out.println("Go fish!");
System.out.println(one.getName() + " drew a card.");
System.out.println();
one.addCard(Card.draw(deck));
one.subSets(one.getHand(), temp3);
deck = Card.getDeck();
turn = "two";
success = "no";
something = one.checkWin();
if (something.equalsIgnoreCase("no"))
System.out.println(one.getName() + " won!");
}
}
//Check player four
if (temp2.equalsIgnoreCase(four.getName()))
{
if (four.searchHand(four.getHand(), temp3) != null)
{
while (four.searchHand(four.getHand(), temp3) != null)
{
one.addCard(four.searchHand(four.getHand(), temp3));
four.subCard(four.searchHand(four.getHand(), temp3));
one.subSets(one.getHand(), temp3);
}
}
else if (four.searchHand(four.getHand(), temp3) == null)
{
System.out.println();
System.out.println("Go fish!");
System.out.println(one.getName() + " drew a card.");
System.out.println();
one.addCard(Card.draw(deck));
one.subSets(one.getHand(), temp3);
deck = Card.getDeck();
turn = "two";
success = "no";
something = one.checkWin();
if (something.equalsIgnoreCase("no"))
System.out.println(one.getName() + " won!");
}
}
}
}
//ALL THE CODE FOR OTHER TURNS HERE
}
//Replay
System.out.println("Would you like to play again?");
something = scan.nextLine();
}
}
}
Player class:
import java.util.*;
public class Player
{
private static String name;
private static Card[] hand = new Card[52];
private static Card[] sets = new Card[52];
private static int handsize = 0, nullcount = 0;
private static String win = "no";
private static int temp = 1; //For subCard
private static int temp2 = 0, temp3 = 0; //For subSets
//Constructor
public Player(String n)
{
name = n;
}
//Mutators
//Add new card to hand
public static void addCard(Card c)
{
hand[handsize] = c;
handsize++;
}
//Lose card that was searched for
public static void subCard(Card c)
{
for (int i = 0; i < hand.length; i++)
{
if (c == hand[i])
{
temp = i;
if (temp < 51)
temp++;
hand[i] = hand[temp];
}
}
hand[(hand.length - 1)] = null;
handsize--;
}
//Lose sets of cards
public static void subSets(Card[] h, Card.rank r)
{
//See if there are four of a kind
for (int i = 0; i < h.length; i++)
{
if (h[i].rank == r)
{
temp2++;
}
}
//Drop set of four
if (temp2 == 4)
{
for (int i = 0; i < h.length; i++)
{
if (h[i].rank == r)
h[i] = null;
for (int ii = (i + 1); ii < (h.length - 1); ii++)
{
temp3 = i;
h[temp3] = h[ii];
temp3++;
}
h[(h.length - 1)] = null;
}
}
hand = h;
}
//Accessors
public static String getName()
{
return name;
}
public Card[] getHand()
{
return hand;
}
public Card searchHand(Card[] h, Card.rank r)
{
for (int i = 0; i < h.length; i++)
{
if (h[i].rank == r)
return h[i];
else if (i == h.length - 1)
return null;
}
}
public String checkWin()
{
for (int i = 0; i < hand.length; i++)
{
if (hand[i] == null)
nullcount++;
}
if (nullcount == (hand.length - 1))
return "no"; //Set equal to something in Program
else
{
nullcount = 0;
return "yes"; //Set equal to something in Program
}
}
}
Card class:
import java.util.*;
public class Card
{
public String suit;
public String rank;
private static int temp = 0, temp2 = 0; //Use for reseting rank and suit
private static Card temp3; //Use for draw method
private static int temp4 = 1; //Use for draw and shuffle, always back to 1
private static Card[] deck = new Card[52];
private static Random random = new Random();
//Constructors
public Card()
{
this.rank = "two";
this.suit = "hearts";
}
public Card(String r, String s)
{
this.rank = r;
this.suit = s;
}
//Mutators
//Make deck
public static void makeDeck(Card[] c, String[] r, String[] s)
{
for (int i = 0; i < c.length; i++)
{
c[i] = new Card(r[temp], s[temp2]);
temp++; temp2++;
//Reset rank and suit
if (temp > 12)
temp = 0;
if (temp2 > 3)
temp2 = 0;
}
deck = c;
}
//Accessors
//Return deck
public static Card[] getDeck()
{
return deck;
}
//Shuffle
public static Card[] shuffle(Card[] c)
{
for (int i = 0; i < c.length; i++)
{
int rand = (int)(random.nextInt(52)*(i + 1));
//Don't let anything be in a slot that doesn't exist
while (rand > c.length)
{
temp4 = random.nextInt(52);
rand -= temp4;
}
if (rand < 0)
{
rand += temp4;
Card temp = c[i];
c[i] = c[rand];
c[rand] = temp;
}
}
deck = c;
temp4 = 1;
return deck;
}
//Draw
public static Card draw(Card[] c)
{
temp3 = c[0];
for (int i = 0; i < c.length - 1; i++)
{
c[i] = c[temp4];
if (temp4 < 51)
temp4++;
}
c[(c.length - 1)] = null;
temp4 = 1;
deck = c;
return temp3;
}
//Return string
public static String toString(Card[] h)
{
String temp5 = "yes";
while (temp5.equals("yes"))
{
for (int i; i < h.length; i++)
{
if (h[i] != null)
return h[i].rank + " of " + h[i].suit +", ";
else temp5 = "no";
}
}
}
}
Card.rank is a string
public class Card
{
public String rank;
So the method declaration needs
public static void subSets(Card[] h, String r)
As For
public Card searchHand(Card[] h, Card.rank r)
{
for (int i = 0; i < h.length; i++)
{
if (h[i].rank == r)
return h[i];
else if (i == h.length - 1)
return null;
}
}
If h.length is zero what are you going to return?