大家好,我想找出第二个最大的否定数组,接受负数。我已经使用了以下代码,并且显示的是正数第二大的数字,所以请建议我该怎么做。

class ArrayExample {
    public static void main(String[] args) {
        int secondlargest = 0;
        int largest = 0;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter array values: ");
        int arr[] = new int[5];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = input.nextInt();
            if (largest < arr[i]) {
                secondlargest = largest;
                largest = arr[i];
            }
            if (secondlargest < arr[i] && largest != arr[i])
                secondlargest = arr[i];
        }
        System.out.println("Second Largest number is: " + secondlargest);
    }
}

最佳答案

用最小的负值初始化变量secondlargestlargest
使用此代码:

class ArrayExample {
        public static void main(String[] args) {
            int secondlargest = Integer.MIN_VALUE;
            int largest = Integer.MIN_VALUE;
            Scanner input = new Scanner(System.in);
            System.out.println("Enter array values: ");
            int arr[] = new int[5];
            for (int i = 0; i < arr.length; i++) {
                arr[i] = input.nextInt();
                if (largest < arr[i]) {
                    secondlargest = largest;
                    largest = arr[i];
                }
                if (secondlargest < arr[i] && largest != arr[i])
                    secondlargest = arr[i];
            }
            System.out.println("Second Largest number is: " + secondlargest);
        }
    }

关于java - 在Java中显示数组中第二大的no,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10716186/

10-10 08:09