0

I declared a string array of 5 phrases. Im having trouble with printing out only one phrase randomly out of the array. My code below generates several phrases. How do I only print out one?

    int length = arr.length;
    
    for (int i = 0; i < length; i++)
    {
        int rand = (int) (Math.random() * length);
        
        System.out.println(arr[rand]);
    }
1
  • 2
    Why the for loop? Is arr the array of phrases? Commented Feb 23, 2021 at 20:55

1 Answer 1

2

Just generate one number and call it to the array index. You dont need for loop because you are not generating multiple numbers. Simple with random.nextInt(arrayWord.length); you generate numbers 0 - array Length

public class RandomNumber {

    public static void main(String[] args) {


        String[] arrayWord = {"Test1", "Test2", "Test3", "Test4", "Tes5"};

        Random random = new Random();

        int randomNumber = random.nextInt(arrayWord.length);


        System.out.println(arrayWord[randomNumber]);
    }
}
Sign up to request clarification or add additional context in comments.

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.