-5

i am new to java programming and now i want to get 4 random values out of an string array i have the following code but if i run my code i get the same random color 4 times.

 String [] color = {"red","blue","yellow", "purple", "black"};
       int random = (int) (4*  Math.random());
        String randomColors = (color[random]);
        for (int i = 0; i <4 ; i++) {
            System.out.println(randomColors);
        }

does anyone know how i can fix this. And again i am new to programming.

wins
  • 1
  • 1

6 Answers6

1

You need to put the random number generator inside the loop:

Random rand = new Random();
for (int i = 0; i < 4 ; i++) {
    int rand_int = rand.nextInt(5); // Generate random integers in range 0 to 4
    String randomColors = (color[rand_int]);
    System.out.println(randomColors);
}

since your index can go up to 4, you should have the random integer value to be in [0, 4], otherwise the last color "black" will never be printed

wenzi
  • 119
  • 1
  • 6
  • I think it's good that you're using the Random class, but if you're taking that approach it's better to put the Random object outside of the loop to avoid unnecessary creations of objects. – Corey Johnson Oct 05 '18 at 13:47
  • 1
    Thanks Corey, revised my code, it is always good practice not to create unnecessary objects. – wenzi Oct 05 '18 at 14:15
0

You almost had the right answer, the only issue is that your int random = statement should be inside the for loop, otherwise you're going to end up with the same random value every time you run through the loop.

String [] color = {"red","blue","yellow", "purple", "black"};

for (int i = 0; i <4 ; i++) {
    int random = (int) (4*  Math.random());
    String randomColors = (color[random]);
    System.out.println(randomColors);
}
0

Just do it over and over again. So instead of creating the random number outside of the loop, do it all inside.

String [] color = {"red","blue","yellow", "purple", "black"};
for (int i = 0; i <4 ; i++) {
    int random = (int) (4*  Math.random());
    String randomColors = (color[random]);
    System.out.println(randomColors);
}
0
Random generator = new Random();
int randomIndex = generator.nextInt(myArray.length);
return myArray[randomIndex];

Repeat this an many times you need a random value.

MR ROBOT
  • 9
  • 5
0

Issue is your random number generator only works a single time. You can resolve this by adding 2nd and 3rd lines of your code inside the for loop you have coded. Good luck!

Lakshitha Wisumperuma
  • 1,574
  • 1
  • 10
  • 17
-1

If you want a new array with random colors you have to declare it and initlize it.

String[] randomColors = String[4];

Then, you have to populate the array with random values of your other array. To get random indexes you do as follow.

for(int i=0; i<5; i++){
randomcolors[i] = colors[(int )(Math.random() * 4 + 0)];
}

To print the new array you use the wrapper class

System.out.println(Arrays.toString(randomcolors));