[英]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.