[英]How to create a list of strings that contain randomly generated numbers in Java?
[英]Java: How to put values into a object from a list of randomly generated numbers
好的,所以我是 Java 新手,这就是我需要做的。 编写一个 Java 程序,允许用户指定他/她希望在 1 到 100 之间生成多少个随机数。然后生成随机数并将它们列在您的输出中。 您还应该计算最高、最低、总和和平均值。 我需要帮助的部分是获得最低和最高。 我不能使用数组,因为我们还没有真正接触过它们。 我需要什么帮助从我的 randomInt 中以最低的 int 值抛出一些东西。
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
Random rnd = new Random();
int r;
int sum = 0;
int lowest=0;
int highest=0;
System.out.println("Please enter enter how many numbers "
+ "you would like to generate.");
int userInput = sc.nextInt();
for(r=1;r<=userInput;r++)
{ // was unsure how to remove the comma from the last number
int randomInt = (int)(rnd.nextFloat()*100)+1;
System.out.print(randomInt + ",");
sum += randomInt;
if(randomInt < lowest)
{
lowest = randomInt;
}
}
System.out.println(" The total sum of these random numbers are "
+sum);
int average = sum / userInput;
System.out.println("The average of all those numbers is "
+ average);
System.out.println(lowest);
}
您的lowest
被分配为 0,您的随机生成数字的范围是 1 到 100。在您的代码中, lowest
值变化的唯一时间是满足条件randomInt < lowest
值时,当然您的程序将始终输出 0 作为最低的。
尝试将lowest
值更改为 100。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.