0

Let's say that I have the following set up:

private String one = "abc";
private String two = "def";
private String three = "ghi";

etc.

I want to write a method that returns a random variable, one of the however many I have declared at the top of the class. Is there an easy way to do this?

0

7 Answers 7

2

What about this simple method? Or do it with a Collection if you have too many elements.

public String getRandomString(){
        Random r = new Random();

        int i = r.nextInt()%3;

        switch (i) {
            case 0:
                return one;
            case 1:
                return two;
            case 2:
                return three;
            default:
                break;
        }

    }
Sign up to request clarification or add additional context in comments.

Comments

2

Two options:

  1. (more complicated) use reflection to get the variables in the class, and select one randomaly.
  2. (simpler) put them in an array, and choose random index.

Comments

0

You could put them into a list and select a random list element by accessing a list element with a random number (You would of course have to check if the random number is inside the range of the list index).

If you need actual example code, comment on this ;-)

The interesting function you would need is math.random()

Comments

0

The easiest and the most convenient way would be to use array instead of variables and then get a random integer and then use this array's index.

Comments

0

You can put them all in a List and then pick a random number between zero and the list size, and pick that element out of the list.

Comments

0

Put your variables in an array or list and use a random number generator to select a random element in that collection.

Comments

-1

I think the accepted solution might return negative values

Java docs nextInt()

  • so you might want to use Math.Abs()
  • or use r.nextInt(3)

java docs nextInt(n)

Related Question

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.