Reputation: 39
I have tried to find out why "%254" sometimes is use in setting colour of Graphics of java,by asking google,but I couldn't find any answer.Can anyone explain?Thanks.
Upvotes: 0
Views: 81
Reputation: 10548
In the sample you gave in comments:
public void paint(Graphics g) {
g.setColor(new Color((int)(Math.random()*1000) % 254, (int)(Math.random()*1000)%254, (int)(Math.random()*1000)%254))
....
}
The %
operator is the modulo operator which takes the remainder of a division operation (rather than the result). I believe module 254 is used here as that there are 255 colours that could be represented. By doing modulo 254 you ensure that the result of Math.random() * 1000
(which will be between 0 and 1000) will never be greater than 255, thus ensuring that you do not go over the 255 limit.
This is part fact and part speculation so I'm open to being proven wrong.
Upvotes: 2