我试图创建一个程序,运行5-10行随机文本从一个-z。我试过运行这个程序,但总是得到一个空白控制台。
public static void main(String[] args) {
// TODO code application logic here
int numberLines = (int) (Math.random() * 5 + 5);
for (int b = 0; b <= numberLines; b++) {
int length = (int) Math.random() * 80;
for (int i = 1; i <= length; i++) {
int randChar = (int) Math.random() * 26;
if (randChar == 0) {
System.out.print("a");
}
else if (randChar == 1) {
System.out.print("b");
}
else if (randChar == 2) {
System.out.print("c");
}
else if (randChar == 3) {
System.out.print("d");
}
else if (randChar == 4) {
System.out.print("e");
}
else if (randChar == 5) {
System.out.print("f");
}
else if (randChar == 6) {
System.out.print("g");
}
else if (randChar == 7) {
System.out.print("h");
}
else if (randChar == 8) {
System.out.print("i");
}
else if (randChar == 9) {
System.out.print("j");
}
else if (randChar == 10) {
System.out.print("k");
}
else if (randChar == 11) {
System.out.print("l");
}
else if (randChar == 12) {
System.out.print("m");
}
else if (randChar == 13) {
System.out.print("n");
}
else if (randChar == 14) {
System.out.print("o");
}
else if (randChar == 15) {
System.out.print("p");
}
else if (randChar == 16) {
System.out.print("q");
}
else if (randChar == 17) {
System.out.print("r");
}
else if (randChar == 18) {
System.out.print("s");
}
else if (randChar == 19) {
System.out.print("t");
}
else if (randChar == 20) {
System.out.print("u");
}
else if (randChar == 21) {
System.out.print("v");
}
else if (randChar == 22) {
System.out.print("w");
}
else if (randChar == 23) {
System.out.print("x");
}
else if (randChar == 24) {
System.out.print("y");
}
else if (randChar == 25) {
System.out.print("z");
}
System.out.println();
}
}我知道有一种更简单的方法来做这件事,但就我的目的而言,我想知道为什么这不起作用。
帮助?
发布于 2016-01-05 07:27:42
我认为你的问题来自于线int length = (int) Math.random() * 80;。这使length始终等于0,因为Math.random()返回在0.0到1.0之间的double,这将转换为0作为int。
您可以尝试添加这样的括号。
int length = (int) (Math.random() * 80);发布于 2016-01-05 07:28:12
来自Math#Random的文档
返回一个带有正号的双值,大于或等于0.0且小于1.0。
因此,基本上,您对length的计算都会生成一个0。双返回值总是小于1。因此,下面对int的强制转换将生成一个0,您的第二个循环将不会被执行。
randchar的计算也会出现同样的情况。
要更改它,可以使用Random类。
Random r = new Random();
...
...
int randChar = r.nextInt(26);https://stackoverflow.com/questions/34606208
复制相似问题