0

I got a String[] from which I want to get a random value. I try to put that logic in another method. This is my code so far.

public static void main(String[]args) {
   String [] S = {"aaa", "bbb", "ccc", "ddd", "eee","ggg", "hhh", "iii", "kkk"};
}

public String get () {
    int i;

    for(i = 0; i <= 4; i++) {

    }
}

I need random strings out of array S with the method get(), but I really don't know how to do it.

3 Answers 3

4

First you'll have to move the S array to be an instance variable or a static variable, because currently it's local to your main method, and can't be accessed from your get method.

Then you can get a random String this way :

private Random rnd = new Random();
public String get ()
{
   return S[rnd.nextInt(S.length)];
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the advice. but if I want to S to remain static variable will it be any other way to write the code.
@Rslh currently S is not a static variable, it's a local variable of the static main method. If you want to keep it there, you can pass it as an argument to the get() method.
Thanks I think I need to review the concept of this language again
0

You can use java.util.Random to generate random things. However, keep in mind that, it is not secure, not really random.

You can get random chars from the array S:

String randomString = ""; 
Random rand = new Random();
for(int i=0;i<=4;i++)
{
    randomString += S[rand.nextInt(S.length())].charAt(0);
}

System.out.println(randomString);

Comments

0

you do not need loop in get() method you need to generate a random number below the length of the original array and say return S[RANDOM_NUMBER]

EDIT

let the get method takes a parameter of String[]

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.