V
V
vitya_brodov2021-01-20 17:15:29
Java
vitya_brodov, 2021-01-20 17:15:29

How to randomly select an object?

Hello!
I wanted to make a Rock Paper Scissors console game.
user is given to choose one of three values, and the Computer chooses randomly one of three options: rock, scissors or paper.
but I don’t know how to implement random for a computer, how can I do this?
user code:

public void gameMethod(){
        Scanner sc = new Scanner(System.in);
        System.out.printf("Вбирете значение: \n 1. %s \n 2. %s \n 3. %s",
                Values.ROCK, Values.PAPER , Values.SCISSORS);
        int userChoice = sc.nextInt();
        Random random = new Random();

    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Roo, 2021-01-20
@vitya_brodov

public enum RockPaperScissors {

    ROCK,
    PAPER,
    SCISSORS;

    public RockPaperScissors getRandomValue() {
       int random = (int) (Math.random() * RockPaperScissors.values().length);
       return RockPaperScissors.values()[random];
    }
}

A
acwartz, 2021-01-20
@acwartz

a + (int) (Math.random() * (b-1)+a)
Where a is the lower limit, b is the upper limit, for example, a \u003d 1, b \u003d 3 - the numbers will be from 1 to 3.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question