How do i put conditionals on certain array indexes

Viewed 681

So i am working on a school assignment in which i need to make a random card generator in java in which i need to shuffle a deck and draw a hand of 5 which i have done and now i need to print the cards in my hand that have a value higher than 9, I've been struggling at this part for days so if anybody could help me it could be amazing.

Here is my code:

package arrays.assignment.pkg1;
import java.util.Arrays;
import java.util.Random;
import javax.swing.JOptionPane;

public class ArraysAssignment1 {

public static void main(String[] args) {
int[] deck = new int[52];
String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", 
"Jack", "Queen", "King"};

// Initialize cards
for (int i = 0; i < deck.length; i++) {
  deck[i] = i;
}

// Display the all the cards
for (int i = 0; i < 52; i++) {
    String suit = suits[deck[i] / 13];
    String rank = ranks[deck[i] % 13];
    System.out.println( rank + " of " + suit);
}
// Shuffle the cards
for (int i = 0; i < deck.length; i++) {
  int index = (int)(Math.random() * deck.length);
  int temp = deck[i];
  deck[i] = deck[index];
  deck[index] = temp;
}
    System.out.println("your deck consists of\n");


System.out.println("\n\nin your hand, you have\n");

// Display 5 cards
for (int i = 0; i <5;i++) {
    String suit = suits[deck[i] / 13];
    String rank = ranks[deck[i] %13];
    System.out.println( rank + " of " + suit);
}
    //Display the cards that are greater than 9
    System.out.println("\nThe cards in your hand that are greater than 9 are\n");
    for (int i = 0; i <5;i++) {
    if(deck[i] > 9) {

        System.out.println(rank + " of " + suit);
    }
}
}

}

and this is all done on netbeans.

2 Answers

First, I would like to point out that your code would be much simpler if you created a Card class

private Class card{
private int Value;
private String Suit;

public card (String suit, int value) {
 Suit = suit;
 Value = value;
}

public int getValue(){
return Value;
} 

public String getSuit(){
return Suit;
}
}

Then you can store all of these cards either in Card[5] Hand, or Card[52] Deck

iterate through your hand and say

if(Hand[i].getValue > 9){
 //do whatever you want to do here
}

Change

for (int i = 0; i <5;i++) {
  if(deck[i] > 9) {
      System.out.println(rank + " of " + suit);
  }
}

to:

for (int i = 0; i <5;i++) {
  String suit = suits[deck[i] / 13];
  String rank = ranks[deck[i] %13];
  if(deck[i] %13 > 9) {
      System.out.println(rank + " of " + suit);
  }
}
Related