【问题标题】:How to clear variable in for loop如何清除for循环中的变量
【发布时间】:2017-09-16 11:38:45
【问题描述】:

这个程序是随机生成 100 个 4 字母数字,它首先生成 4 个字母,然后再生成 4 个并将它们添加到函数中。我猜这是因为我使用了.append。我尝试输入 random = "";在循环的顶部和底部,但它只是清除了变量。有没有其他方法可以做到这一点,或者有什么可以添加到程序中的吗?

    Random input = new Random();
    StringBuilder in = new StringBuilder();

    String alphabet = "abcdefghijklomnpqrstuvwxyz";
    char[] letterPool;
    letterPool = alphabet.toCharArray();
    for(int y = 0; y < 101; y++){
    for(int x = 0; x<4; x++){
        in.append(alphabet.charAt(input.nextInt(alphabet.length())));

    }

    String random=in.toString();


    System.out.println(random);

    System.out.println("space");
    }

【问题讨论】:

  • 嗯??

标签: string loops append


【解决方案1】:
Random input = new Random();
String alphabet = "abcdefghijklomnpqrstuvwxyz";
for (int y = 0; y < 100; y++) {
    StringBuilder in = new StringBuilder();
    for (int x = 0; x < 4; x++) {
        in.append(alphabet.charAt(input.nextInt(alphabet.length())));

    }
    String random = in.toString();
    System.out.println(random);
}

【讨论】:

  • 谢谢!为什么在 for 循环之间移动 StringBuilder 可以解决它?
  • 这样,在外部for循环的每次迭代中,StringBuilder都会被重新初始化。
【解决方案2】:

每次外部 for 循环完成时,内部 for 循环都会自行重置。

【讨论】:

    猜你喜欢
    • 2022-10-15
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 2017-06-20
    • 1970-01-01
    • 2023-03-28
    • 2017-03-22
    相关资源
    最近更新 更多