public class Exercise16 {
public static void main(String[] args) {
int a = (int) (Math.random() * 27 + 63);
System.out.println(a);
char b = (char) a;
System.out.println(b);
}
}
Math.random()是取0.0到1.0之间的伪随机数,也就是说有可能取到0。或者一个乘以27小于1的数,自然取到ascii码是63或是64的值了,只是取0的概率
比较小,不然你可以看到“>”
int a = (int) (Math.random() * 27 + 64);
Math.random()产生一个0~1的整数,因为<1所以取整只能得到0~26,可以取到0
有两点要说明:1.math产生的随机数,是0~1包前不包后,这种现象在API中很常见。依你所写,取值就是63<=a<90。63改成65,27改成26,就好。2.优化,字符可作为int型数据参与运算。把65改成字符A,提高阅读性。
在连续整数中取得一个随机数
值 = Math.floor(Math.random() * 可能值的总数 + 第一个可能的值)
int a = (int) (Math.random() * 26 + 65);