+ 2

WHY I am not getting random values between 0 & 6 using following codes ?

public class Program { public static void main(String[] args) { for(int i=0;i<6;i++) { int c=1+(int)Math.random()*6; System.out.println(c); } } } I am getting just 1 1 1...

23rd Mar 2017, 7:15 AM
Mr.Curious
Mr.Curious - avatar
2 Antworten
+ 8
It's because Math.random() which returns a number in [0,1) will always be zero when converted to int. So, your code is nothing but: int c=1+0*6; To get what you want, use this: int c=1+(int)(Math.random()*6)
23rd Mar 2017, 7:38 AM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
+ 1
Oh, Thanks , I forgot to give the brackets, that why I am getting it.
26th Mar 2017, 12:18 PM
Mr.Curious
Mr.Curious - avatar