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. 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.
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
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 .
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. 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..
另外,考虑到这是一个家庭作业问题,最好不要对整个数组进行排序,因为这样会得到O(n * logn)复杂度,但是要遍历值并仅保留最大的两个值(n)复杂性。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.