簡體   English   中英

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM