Rob
Rob

Reputation: 35

How to display a certain string for an integer?

I have to make a Poker Dice game for class. I am able to successfully random five numbers 1 to 6 (to resemble rolling a die five times). However, I need to show "Nine" for 1, "Ten" for two, etc. I am using an array to hold the numbers. I can't seem to figure out how to assign a string output for each int.

public static void main(String[] args) {

    int[] player = new int[5];
    String[] cards = new String[] {"Nine", "Ten", "Jack", "Queen", "King", "Ace"};

    System.out.println("User: " + playerHand(player, cards));

}
public static String playerHand(int[] player, String[] cards) {
    String hand = "";
    for (int i = 0; i < player.length; i++) {
        player[i] = (int) (Math.random() * (6 - 1) + 1);
        hand += player[i] + " ";
    }

    return hand;
    }

Upvotes: 0

Views: 53

Answers (2)

Hoopje
Hoopje

Reputation: 12932

You've put your strings in an array, so you just add an element from the array to your hand string:

hand += cards[player[i]] + " ";

There is, however, still a problem with your code. You obtain the random numbers as follows:

player[i] = (int) (Math.random() * (6 - 1) + 1);

You probably expect this to be a number from 1 to 6. However, Math.random() returns a double from 0 (inclusive) to 1 (exclusive). That means that player[i] will never be assigned 6. This error kind of solves another error: since Java arrays are zero-based, the element with index 6 does not exist. (Thus, if 6 would have been chosen, your program would have aborted with an error message.) But still, the number 0 and thus the word "Nine" will never appear in your solution. So you have to change the two lines to:

hand += cards[player[i] - 1] + " ";

and

player[i] = (int) (Math.random() * 6 + 1);

respectively.

Consider making the cards array a static class member; then you don't need to pass the array to the playerHand method as an argument.

Upvotes: 1

Alex
Alex

Reputation: 105

You might use a switch block

switch(array[i]){
case 1:
printf("One\n");
break;
case 2:
printf("Two\n");
break;

etc...

Upvotes: 0

Related Questions