so for a homework task I have to make a program that deals N(command line input) amount of poker decks (5 cards). I have a for-loop that checks if a card has been used, but nonetheless duplicate cards get printed. Any help would be greatly appreciated.
Code that checks for duplicates
do {///check for dupes
bUsed = false;
randS = (int) (Math.random() * 4);
randV = (int) (Math.random() * 13);
for (int k = 0; k < 52; k ) {
value[randV]);
if ((used[k] == (suit[randS] value[randV])) && (used[k] != null)) {
bUsed = true;
}
}
} while (bUsed);///end check
Full code
public class Deal {
public static void main(String[] args) {
String[] suit = {"Hearts", "Diamonds", "Spades", "Clubs"};
String[] value = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
String[] used = new String[52];
boolean bUsed = false;
int usedC = 0;
int N = Integer.parseInt(args[0]);
// int N = 4;
if (N <= 10) {
/////////check for max
for (int i = 0; i < N; i ) {/////////print N amount of decks
System.out.println("Deck " (i 1));
for (int j = 0; j < 5; j ) {/////////print 5 cards
int randV = 0;
int randS = 0;
do {///check for dupes
bUsed = false;
randS = (int) (Math.random() * 4);
randV = (int) (Math.random() * 13);
for (int k = 0; k < 52; k ) {
if ((used[k] == (suit[randS] value[randV])) && (used[k] != null)) {
bUsed = true;
}
}
} while (bUsed);///end check
used[usedC] = suit[randS] value[randV];
System.out.println(suit[randS] " " value[randV]);
usedC ;
}////end print 5 cards
System.out.println();
}///end print amount of decks
} else {
System.out.println("Too many decks requested");
}
}
}
Example of output
java Deal.java 5 Deck 1 Clubs 6 Clubs 10 Clubs J Hearts Q Spades J
Deck 2 Hearts 4 Hearts 7 Hearts A Clubs J Diamonds 3
Deck 3 Spades K Diamonds 3 Diamonds Q Diamonds 4 Clubs 2
Deck 4 Spades 7 Diamonds 7 Diamonds 3 Clubs A Diamonds 9
Deck 5 Clubs 2 Spades 4 Diamonds 4 Diamonds 3 Spades 7
CodePudding user response:
You are comparing Strings with ==
instead of .equals()
.
This is the problematic line:
if ((used[k] == (suit[randS] value[randV])) && (used[k] != null))
First of all you need to flip the null-check and the value-check, to prevent a NullPointerException, since .equals()
is a method call (for the operator ==
this would not matter). Then use the method for comparison, like:
if ((used[k] != null) && used[k].equals(suit[randS] value[randV]))
Besides that you would make your life a lot easier, if you used a List<String>
for used instead of an array, because there you could then simply use the .contains
method instead of your own loop - but I don't know if that is allowed for your homework.
To make your program a little bit faster, you can add a break;
statement at the end inside the if-block, as you can break out the for-loop as soon as you find a duplicate.