[英](Java) How do i make those loops generate a new string every time?
Ok, so hoehe
and breite
are two ints that are grabbed from console input earlier.好的,所以
hoehe
和breite
是之前从控制台输入中获取的两个整数。 This works flawlessly.这完美无缺。 Now I want it to generate a random string with the lenght being the value of breite, print that out and then do that hoehe times.
现在我希望它生成一个随机字符串,长度为 breite 的值,将其打印出来,然后执行 hoehe 次。 The only Characters the string can have are
/
and \
.字符串可以包含的唯一字符是
/
和\
。 Right now it generates the string one time and then prints it out hoehe times.现在它会生成一次字符串,然后将其打印出 hoehe 次。
int i = 0;
int y = 0;
double rand;
String output = "";
String case1 = "/";
String case2 = "\\";
while (y < hoehe) {
while (i < breite) {
rand = Math.random();
if (rand < 0.5) {
output += case1;
}
else {
output += case2;
}
i++;
}
System.out.println(output);
y++;
}
You never reset i
.你永远不会重置
i
。 Use for-loops instead:改用 for 循环:
double rand;
String output = "";
String case1 = "/";
String case2 = "\\";
for(int y = 0; y < hoehe; ++y) {
for(int i = 0; i < breite; ++i) {
rand = Math.random();
if (rand < 0.5) {
output += case1;
}
else {
output += case2;
}
}
System.out.println(output);
}
}
int i = 0;
int y = 0;
double rand;
String output = "";
String case1 = "/";
String case2 = "\\";
while (y < hoehe) {
while (i < breite) {
rand = Math.random();
if (rand < 0.5) {
output += case1;
}
else {
output += case2;
}
i++;
}
i = 0; ////// add this
System.out.println(output);
y++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.