-4

How can I stop the color from being chosen in a row?

I'm trying to avoid repeating the same colors in a row chosen from the array. I have tried comparing if the colors are equal but haven't been able to skip the color when chosen randomly again.

Color color[]={Color.YELLOW,Color.MAGENTA,Color.BLACK,new Color(0x964B00),new Color(0xB57EDC)};

Random rand=new Random();
Color newColor = color[rand.nextInt(5)];

for(int i=0;i<5;i++){
    if(newColor.equals(color[i]));{
        newColor=color[rand.nextInt(5)];
    }
    myPanel.colorArray[myPanel.mouseDownGridX][myPanel.mouseDownGridY] = newColor;
    myPanel.repaint();
}
Dav1497
  • 3
  • 2
  • I'm trying to avoid repeating the same colors in a row chosen from the array. I have tried comparing if the colors are equal but haven't been able to skip the color when chosen randomly again. – Dav1497 Mar 17 '17 at 18:50
  • 1
    What's your question? – Gregg Mar 17 '17 at 18:50
  • Why is it so far indented? I suspect you must have a lot of nesting. – weston Mar 17 '17 at 18:52
  • Sorry I am a new user in StackOverflow. My question is the comment below the code. How can I stop the same color from being chosen in a row? – Dav1497 Mar 17 '17 at 18:54
  • @Dav1497 I cleaned up the question a bit, you can delete that comment with your actual question. – fvu Mar 17 '17 at 18:56
  • it is very unclear what you try to do and if i read your explanation and you code snippet – muescha Mar 17 '17 at 22:51
  • 1
    Possible duplicate of [Semicolon at end of 'if' statement](http://stackoverflow.com/questions/14112515/semicolon-at-end-of-if-statement) – Tom Mar 17 '17 at 23:10
  • @Tom good catch :) – muescha Mar 19 '17 at 21:11

1 Answers1

1

Your question is not very clear and your current code shows a small selection size that will repeat often. This is a possible solution if your question is understand as:

How to create a random number where the new number is not the previous one?

(note: code is from scratch - it should show the main idea in randomExclude)

Color color[]={Color.YELLOW,Color.MAGENTA,Color.BLACK,new Color(0x964B00),new Color(0xB57EDC)};

// remember the previous color somehow
int previousColorIndex = 0;

// -----

newColorIndex = randomExclude(previousColorIndex)

myPanel.colorArray[myPanel.mouseDownGridX][myPanel.mouseDownGridY] = color[newColorIndex];
myPanel.repaint();

previousColorIndex = newColorIndex

// -----

public static int randomExclude(int previous)
{
  Random rand=new Random();
  int random =rand.nextInt(5);

  if(previous == random)
    {
        return randomExclude(previous);
    } 
  }

  return random;
}
Alexander
  • 540
  • 6
  • 12
muescha
  • 1,544
  • 2
  • 12
  • 22
  • @Dav1497 if this answer solved your problem, please accept this answer: click at the grey checkmark on the left side of the answer. – muescha Mar 19 '17 at 21:09