有人可以解释为什么程序1只重复打印一个随机数吗?而下面的程序2打印100个随机数?另外,是否有编辑程序1来执行程序2的操作?
计划1
public class RandomComparison {
public static void main(String[] args){
int rnd = (int) Math.random() * 6 + 1;
for(int i=0; i<100; i++){
System.out.print(rnd);
}
}
}
计划2
public class RandomPractice {
public static void main (String[] args){
int roll;
String msg = "Here are 100 random rolls of the dice:";
System.out.println(msg);
for (int i=0; i<100; i++){
roll = randomInt(1, 6);
System.out.print(roll);
}
}
public static int randomInt(int low, int high){
int result = (int) (Math.random()*(6) + low);
return result;
}
}
答案 0 :(得分:0)
在第一种方法中,您将检索一次随机值并将该单个值打印100次。第二种方法是生成一个随机数100次,并在每次迭代时打印它。
int rnd = (int) Math.random() * 6 + 1;//grabbed only once
for(int i=0; i<100; i++){
System.out.print(rnd);//printing `rnd` 100 times
}
for (int i=0; i<100; i++){
roll = randomInt(1, 6);//calling for a new random number with each iteration, then printing it
System.out.print(roll);
}
并正确使用您的randomInt
方法:
public static int randomInt(int low, int high){
int result = (int) (Math.random()*(high) + low);//replace `6` with the parameter `high`
return result;
}
要修复第一个方法,让它与第二个方法一样运行:
public class RandomComparison {
public static void main(String[] args){
for(int i=0; i<100; i++){
System.out.print((int)(Math.random()* 6) + 1);//prints out a random number with every iteration
}
}
}