-1

I was just wondering if there's a way to combine some of these statements. I believe there's a way to assign two things at once, I'm just having trouble remembering the syntax.

    // Selects two cards for the player.
    choosePlayerFirstNumber = r.nextInt(12);
    choosePlayerFirstSuit = r.nextInt(3);
    choosePlayerSecondNumber = r.nextInt(12);
    choosePlayerSecondSuit = r.nextInt(3);
    

    // Selects two cards for the dealer.
    chooseDealerFirstNumber = r.nextInt(12);
    chooseDealerFirstSuit = r.nextInt(3);
    chooseDealerSecondNumber = r.nextInt(12);
    chooseDealerSecondSuit = r.nextInt(3);


    suits = new String[]{"Hearts", "Diamonds", "Clubs", "Spades"};
    number = new String[]{"An Ace", "A 2", "A 3", "A 4", "A 6", "A 7", "An 8", "A 9", "A 10", "A Jack", "A Queen", "A King"};
Tony
  • 618
  • 12
  • 27
  • The suggestion from @NicoVanBelle might be what you asked for, but it might not be what you want. Your code and the suggestion are not equivalent! In your code the call to ``Random.nextInt` is really called twice. – Seelenvirtuose Jun 15 '21 at 15:07
  • 1
    This code allows selection of the same cards/suits several times. You should create objects representing a card and a deck of cards, shuffle the deck and pick the cards from the deck. – Nowhere Man Jun 15 '21 at 15:17
  • 1
    Avoid [magic numbers](https://stackoverflow.com/q/47882). Instead of `choosePlayerFirstNumber = r.nextInt(12);` clearer code would probably be `choosePlayerFirstNumber = r.nextInt(allNumbers.size());` (which brings second suggestion, rename `number` to something like `allNumbers`). This will probably also prevent you from making mistakes like `r.nextInt(3);` which will never let you get `Spades`. – Pshemo Jun 15 '21 at 15:19

1 Answers1

0

The first thing to notice is that you need two information to point to a card: Its suit and its value. So that could be a class, like this:

class Card {
  int value;
  int suit;
}

You could then create a player which is holding two cards:

class Player {
  Card first, second;
}

Now you need to assign the randomness, but beware that what you did is not realistic in a card-play setup, you can have multiple cards with the same value and same suit! So you might want to create a list with all possible cards and randomly draw from that for added realism.

If you don't care about this detail, you can simply assign the values in the constructor.

public class Card {
  private static Random r=new Random();
  public Card(){
    this.value=r.nextInt(12);
    this.suit=r.nextInt(4);
  }
  public final int value;
  public final int suit;
}

And then you can create the cards when you create the player object:

public class Player {
  public Player(){
    first=new Card();
    second=new Card();
  }
  public final Card first, second;
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Karsten Becker
  • 502
  • 5
  • 11