V
V
vitya_brodov2020-10-02 22:30:25
Java
vitya_brodov, 2020-10-02 22:30:25

How to randomly select elements from an array?

Hello!
There is a class in which there are two arrays (card suit and value)
I can’t make it so that I randomly select suits and value and enter on the screen
something like this should be:

K ♠, 2 ♦, Q♥, A♣
Подскажите пожалуйста что я делаю не так?


My code:
public  class Card {

    private  String[] values  = {"2", "3", "4", "5", "6", "7", "8", "9", "10",
    "J", "Q", "K", "A"};

    private String[] suit = {"\u2660", "\u2665", "\u2666", "\u2663"};


    // метод для подбора масти
    public  void getSuit(){
        int randomSuit = new Random().nextInt(suit.length);
        switch (randomSuit){
            case 0: System.out.print("\u2660" );
            break;
            case 1: System.out.print("\u2665");
            break;
            case 2: System.out.print("\u2666");
break;
            case 3: System.out.print("\u2663");
break;
        }
    }

    // метод для подбора 4 случайных значений из массива values
    void getValues(){
        Random random = new Random();
        int numberOfElements = 4;
        for (int i = 0; i < numberOfElements; i++){
            int randomIndex = random.nextInt(values.length);
            System.out.print(randomIndex);
        }

    }

    void displayCard(){
        getSuit();
        getValues();
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2020-10-02
@vitya_brodov

1. Arrays are declared, but their values ​​are not used.
2. You get four random numbers and simply display them on the screen, again without using the values ​​from the array.
3. The business logic of the class is not clear, but is it clear what it should display, a map? Suit? Meaning?
4. You need a loop that will get one suit and one value.
Well, the answer to the question. Random elements from arrays are obtained like this:

private void getSuit() {
        int randomSuit = new Random().nextInt(suit.length);
        System.out.print(suit[randomSuit]);
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question