簡體   English   中英

在Java中隨機生成的數組中找到第二高的數字

[英]finding the secondhighest number in a randomly generated array in java

大家好,我遇到一個作業問題,要求我找到隨機生成的數組的第二高數字並返回該數字。 該數組的長度必須為6,因此從概念上講,這是我遇到編譯器錯誤牆之前的內容。 有人可以幫我完成嗎? 更新:我需要引用數組,並在主要方法中調用它,試圖在system.out.println語句中這樣做,但是我不知道如何調用適當的方法/數組。

import java.io.*;
import java.util.Arrays; 

public class SecondHighest{
 public static int find2ndHighest(int[] list){
//define how long the array can be
list[] = new int[6];
    //create a for loop to fill the array.
for(int i = 0; i>=list.length; i++){
  list[i] = (int)(Math.random()*10);

}
  Arrays.sort(list);    //use the built-in sorting routine
  return list[1];

}
}

您的循環永遠無法正常工作,因為i永遠不會大於或等於 list.length

更改

for(int i = 0; i>=list.length; i++){

for(int i = 0; i<list.length; i++){

它應該小於,因為Array索引從零開始,以Arraylength-1結束

也改變

list[] = new int[6];// this is wrong 

 to 

list = new int[6]; // you dont need sqare brackets, you only need array reference.

閱讀您的編譯器錯誤! 有很多語法錯誤,例如在將其作為參數后調用list-> list []。 您可以稱之為清單! 此外,您不必在方法內部創建新列表! 應該是這樣的:

 import java.io.*;
    import java.util.Arrays; 

    public class SecondHighest{

     public static int find2ndHighest(int[] list){

        //create a for loop to fill the array.
    for(int i = 0; i<list.length; i++){
      list[i] = (int)(Math.random()*10);

    }
      Arrays.sort(list);    //use the built-in sorting routine
      return list[1];
    }

     //define how long the array can be
      int[] list = new int[6];
      int result = find2ndHighest(list);

    }

我不確定使用Math隨機函數。

另外,考慮到這是一個家庭作業問題,最好不要對整個數組進行排序,因為這樣會得到O(n * logn)復雜度,但是要遍歷值並僅保留最大的兩個值(n)復雜性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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