我目前正在尝试使用 Java,因为我仍在学习基础知识。 我想知道是否可以通过某种方式使用带变量的 for 循环。
以这段代码为例:
public class Var {
public static void main(String[]args) {
int num1 = (int) (Math.random() * 6) + 1;
System.out.println("First dice: " + num1)
int num2 = (int) (Math.random() * 6) + 1;
System.out.println("Second dice: " + num2);
int num3 = (int) (Math.random() * 6) + 1;
System.out.println("Third dice: " + num3);
}
}
下面是我使用 for 循环描绘代码的方式
public class Var {
public static void main(String[]args){
for (int i = 1; i <= 3; i++) {
int num(i) = (int) (Math.random() * 6) + 1; //Here i is the for loop
System.out.println("num(i)");
}
}
}
这里显然有几个语法错误,但是有没有办法制作类似于此的代码?
有什么建议吗?谢谢!
最佳答案
You're looking for the array syntax:
int[] accumulator = new int[3]; // create a new array
for (int i = 0; i < 3; i++) { // loop
int num = (int) (Math.random() * (6)+1);
accumulator[i] = num; // assign the random number
System.out.println(accumulator[i]); // print to console
}
关于java - 相同的变量,不同的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50761882/