class num{
public static void main(String[] args){
char ch;
//System.out.print((char)(65)); //大写字母A对应65
//System.out.print((char)(90)); //大写字母Z对应90
for(int j=0;j<5;){ //控制生成随机字母的个数,取五个
int i=(int)(128*Math.random());
//System.out.println("i is "+i); //查看生成的随机数
if (i>64 && i<=90){
ch=(char)(i);
//System.out.println("The initial ch is "+ch);//随机数对应的字母
//随机数对应的如果不是元音字母,则打印输出,且控制变量j加一
if (ch!='A' && ch!='E' &&ch!='I' && ch!='O' &&ch!='U'){
j=j+1;
//System.out.println("j is "+j);
System.out.println(ch);
}
}
}
}
}
因为Math.random()是0.0~1.0(不包括1.0)之间的double型随机数,所以上面红色的部分也可以这么写:
int i=(int)(26*Math.random()+64);
运行结果:
W
L
S
G
B
该博客介绍了一段Java代码,用于生成并输出5个随机的大写英文字母,但排除所有的元音字母。通过使用Math.random()函数配合字符转换,确保生成的字母符合要求。
388

被折叠的 条评论
为什么被折叠?



