gpt4 book ai didi

java - 随机字符串程序

转载 作者:行者123 更新时间:2023-12-01 16:54:52 24 4
gpt4 key购买 nike

我正在尝试创建一个运行 5-10 行 a-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();
}
}

我知道有一种更简单的方法可以做到这一点,但出于我的目的,我想知道为什么这不起作用。

帮忙?

最佳答案

我认为您的问题来自行int length = (int) Math.random() * 80;。这使得 length 始终等于 0,因为 Math.random() 返回 0.0 和 1.0 之间的 double,它将被转换为 0 作为int

你可以尝试添加这样的括号

int length = (int) (Math.random() * 80);

关于java - 随机字符串程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34606208/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com