简体   繁体   English

(Java)如何让这些循环每次都生成一个新字符串?

[英](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.好的,所以hoehebreite是之前从控制台输入中获取的两个整数。 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.

相关问题 新来java; 如何在条件语句中生成字符串 static? - New to java; how do I make the String static within conditionals? 如果每次制作新游戏都在网格中生成这些按钮,是否必须在xml中定义屏幕上的每个按钮? - Do I have to define every button on screen in xml if those buttons are generated in a grid every time a new game is made? 每次创建一个新对象时,如何在 Java 中增加类变量中的数量? - How to increase the number in a class variable in Java every time I make a new object? 每次更改变量时如何生成事件流? - How Do I Generate Event Stream Every Time Variable Is Changed? 如何使用Java在循环中使该表为0-9? - How do I make this table 0-9 with loops in Java? Java:您可以在每次循环时更改同一字符串的值吗? - Java: can you change the value of the same string every time it loops? 每次程序循环时如何创建新对象? - How can I create a new object every time my program loops? 我需要制作一个带有for循环的字符串三角形,每次取一个单词的字母。 爪哇 - I need to make a string triangle with for loops taking off one letter of the word each time. Java Android Studio-每次单击按钮时如何在线性布局上生成新的textview - Android Studio - How can I generate a new textview on my linear layout every time i click a button 如何创建一个带有“字符”的字符串?(Java) - How do I make a string with a " character in it? (Java)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM