简体   繁体   中英

Given a String of numbers separated by one or more spaces, find the 2nd largest number

So here's what I got so far:

    public static int findSecondLargest(String nums){

    String[] num = nums.split(" ");
    int[] numbers = new int[num.length];
    int highest1 = Integer.MIN_VALUE;
    int highest2 = Integer.MIN_VALUE;

    for (int i =0; i < num.length; i++) {       
        numbers[i] = Integer.parseInt(num[i]);
    }

    for (int numbers : numbers) {
        if (numbers >= highest1) {
            highest2 = highest1;
            highest1 = numbers;
        }
        else if (numbers > highest2) {
            highest2 = numbers;
        }
    }
    return highest2;
}

I'm getting an error on the line for (int numbers : numbers) { because it's a duplicate, but I'm still not sure why my code shouldn't work, since I want to use the full range of the array in the for loop.

Any suggestions? Also, is there an easier way to do this without using an array?

for (int numbers : numbers) {

This is the same variable in both places. Is the variable numbers an int or an int[] ? You can't tell and neither can the compiler. Rename that variable.

I would recommend changing the first numbers to i or some other variable. The compiler may think that you are trying to run an array through an array.

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.

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