Java初学者。但是有C和Python的历史。
我正在尝试使用此代码:
package javaman;
import java.util.Random;
public class JavaMan{
public static void main(String[] args) {
Random random = new Random();
int randomInteger = 0;
float average = 0;
System.out.println("The 3 Numbers are:");
for (int i=0; i<3; i++) {
randomInteger = random.nextInt(51);
System.out.println(randomInteger);
average = average + randomInteger;
}
average = average/3;
System.out.println("The average of the three random numbers (between 0-50) is: " + average);
}
}
并使其打印出以下内容:
The 3 Numbers are:
Number 1 is: 32
Number 2 is: 16
Number 3 is: 0
The average of the three random numbers (between 0-50) is: 16.0
然而,我已经编程了这样,每当我使用randomInteger时,它只是在我希望for循环有自己的for循环时运行整个for循环(整个“Number x is:”不存在...它只是打印3个数字并吐出平均值):从某种意义上说,我会像以下那样......
("Number", i, "is:", randomInteger) this would look like "Number 1 is: 16"
("Number", i, "is:", randomInteger) this would look like "Number 2 is: 15"
("Number", i, "is:", randomInteger) etc.
如何在Java中创建它?
答案 0 :(得分:1)
只需添加System.out.println ("Number "+i+" is:"+randomInteger);
public static void main(String[] args) {
Random random = new Random();
int randomInteger = 0;
float average = 0;
System.out.println("The 3 Numbers are:");
for (int i=0; i<3; i++) {
randomInteger = random.nextInt(51);
// System.out.println(randomInteger);
System.out.println ("Number "+i+" is:"+randomInteger);
average = average + randomInteger;
}
average = average/3;
System.out.println("The average of the three random numbers (between 0-50) is: " + average);
}