首页 > 解决方案 > (Java)如何让这些循环每次都生成一个新字符串?

问题描述

好的,所以hoehebreite是之前从控制台输入中获取的两个整数。这完美无缺。现在我希望它生成一个随机字符串,长度为 breite 的值,将其打印出来,然后执行 hoehe 次。字符串可以包含的唯一字符是/\。现在它会生成一次字符串,然后将其打印出 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++;

}

标签: javaloops

解决方案


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++;
  }

推荐阅读