Main Class:
public class Blackjack {
static Deck D;
static Hand P;
public static void main(String[] args) {
init();
}
private static void init() {
D=new Deck();
P=new Hand(D);
startGame();
}
private static void startGame() {
System.out.print("Your cards are: "+P.H.get(0)+", "+P.H.get(1));
}
}
Hand Class:
import java.util.ArrayList;
import java.util.Random;
public class Hand {
ArrayList<String> H;
Random R;
public Hand(Deck D){
R=new Random();
H=new ArrayList<String>();
int C=R.nextInt(D.getP().length);
H.add(D.getP()[C]);
D.removeFromDeck(C);
int E=R.nextInt(D.getP().length);
H.add(D.getP()[E]);
D.removeFromDeck(E);
}
}
Deck Class
public class Deck {
String[] P;
public Deck(){
P=new String[52];
String Suit="Default";
int C=0;
for(int A=1;A<=4;A++){
switch(A){
case 1:
Suit="Hearts";
break;
case 2:
Suit="Diamonds";
break;
case 3:
Suit="Clubs";
break;
case 4:
Suit="Spades";
break;
}
for(int B=1;B<=13;B++){
if(B>10){
switch(B){
case 11: P[C]="Joker of "+Suit;
break;
case 12: P[C]="Queen of "+Suit;
break;
case 13: P[C]="King of "+Suit;
break;
}
}else{
P[C]=B+" of "+Suit;
}
}
}
}
public void setP(String[] p) {
P = p;
}
public String[] getP() {
return P;
}
public void removeFromDeck(int C){
System.arraycopy(P, C + 1, P, C,
P.length - C - 1);
}
}
When I compile and run this code, it prints that my 2 cards are null, null. I have looked through the code and can’t seem to find my error. Maybe you can? TY for any help you give me.
Edit: It is now returning spades only, could someone please help?
Both your loops have conditions the wrong way round:
Neither of these will execute any iterations. They should be:
Additionally, you’re not allocating enough size:
There are 52 cards in a back, not 51.
EDIT: As noted in comments, you’ll always get spades with the code as posted, because your switch statement to select the suit doesn’t have any breaks in. I would have expected this to result in a compile-time warning. You really should pay attention to warnings. You can add break statements like this:
Finally, I would strongly advise you to use more meaningful variable names, preferrably following Java naming conventions. (There are actually various other changes I’d make to your code, but start off with those.)