简体   繁体   English

在Java中随机生成的数组中找到第二高的数字

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

Hey guys I have a homework problem that asks me to find the second highest number of a randomly generated array and to return that number. 大家好,我遇到一个作业问题,要求我找到随机生成的数组的第二高数字并返回该数字。 the array has to be of length 6 and so conceptually this is what i have before i run into a wall of compiler errors. 该数组的长度必须为6,因此从概念上讲,这是我遇到编译器错误墙之前的内容。 can someone please help me finish it? 有人可以帮我完成吗? update: I need to reference the array and call it in the main method im trying to do so in a system.out.println statement however i dont know how to call the proper method/array. 更新:我需要引用数组,并在主要方法中调用它,试图在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];

}
}

your loop would never work as i would never be greater than or equal to list.length 您的循环永远无法正常工作,因为i永远不会大于或等于 list.length

change 更改

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

to

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

it should be less than because, Array indexes start from zero and end at Arraylength-1 . 它应该小于,因为Array索引从零开始,以Arraylength-1结束

also change 也改变

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

 to 

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

Read your compiler errors! 阅读您的编译器错误! There are many syntax errors, like calling list -> list[] after you got it as a parameter. 有很多语法错误,例如在将其作为参数后调用list-> list []。 You can just call it list! 您可以称之为清单! Furthermore you don't have to create a new list inside your method! 此外,您不必在方法内部创建新列表! Should be something like this: 应该是这样的:

 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);

    }

I'm not sure with the Math random function.. 我不确定使用Math随机函数。

另外,考虑到这是一个家庭作业问题,最好不要对整个数组进行排序,因为这样会得到O(n * logn)复杂度,但是要遍历值并仅保留最大的两个值(n)复杂性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM