我了解了 for 循环的一般要点。我想知道如何向初始值设定项添加两个变量。我还想同时计数计数器和随机数。我希望它随机打印,但不打印 30 个相同的数字
public class forLoop {
public static void main(String[] args) {
int random = (int) (Math.random() *50) +25;
for(int counter = 0; counter < 30; counter++){
System.out.println(random);
}
}
}
最佳答案
您正在循环之外生成随机数。因此它每次都会以相同的数字存在。解决方案是将定义移到循环内。
public static void main(String[] args) {
for(int counter = 0; counter < 30; counter++){
int random = (int) (Math.random() *50) +25;
System.out.println(random);
}
}
这样,每次循环(30 次迭代)时,您的代码都会 (1) 生成一些随机数并 (2) 打印该数字。
关于java - for 循环程序的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17803304/