Java程序中求数组中最大值的编译问题

问题描述 投票:0回答:4

这是我正在处理的代码片段,我的目标是使用预定义的 Java 方法从列表中找到最大值。

import java.util.*;

public class Test {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("Enter a list of integers: ");
        int array[] = new int[10];

        for (int i = 0; i < array.length; i++) {
            array[i] = s.nextInt();
        }

        for (int j = 0; j < array.length; j++) {
            if (j < array.length) {
                int maximum = Math.max(array[j], array[j + 1]);
            }
        }

        System.out.println("Largest number of the list: " + maximum);
    }
}

我收到的错误如下:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
        maximum cannot be resolved to a variable

如何解决这个问题?

java arrays variables scope max
4个回答
2
投票

您可以迭代数字数组并跟踪看到的最大值:

int largest = Integer.MIN_VALUE;

for (int j=0; j < array.length; j++) {
    if (array[j] > largest) {
        largest = array[j];
    }
}

注意:上面的代码片段假设您在输入数组中至少有一个数字。


0
投票
  1. 您可以使用

    IntStream.max()
    方法来查找
    int
    基元流的最大元素:

    int[] arr = {4, 7, 5, 3, 2, 9, 2, 7, 6, 7};
    
    int max = Arrays.stream(arr).max().getAsInt();
    
    System.out.println(max); // 9
    
  2. 您可以使用

    Stream.max(Comparator)
    方法来查找
    Integer
    对象流的最大元素:

    List<Integer> list =
            Arrays.asList(6, 10, 2, 1, 6, 4, 5, 8, 9, 8);
    
    Integer max2 = list.stream()
            .max(Comparator.comparingInt(Integer::intValue))
            .get();
    
    System.out.println(max2); // 10
    

另请参阅:
如何在二维数组中找到前5个最高值?
Java 中数组的选择排序


0
投票

如上所述,注意变量范围:

public class Test {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("Enter a list of integers: ");

        int array[] = new int[10];
        for (int i = 0; i < array.length; i++) {
            array[i] = s.nextInt();
        }

        int maximum = 0;
        for (int j = 0; j < array.length - 1; j++) {
            maximum = Math.max(array[j], array[j + 1]);
        }

        System.out.println("Largest number of the list: " + maximum);
    }
}

0
投票

您在 for 循环块内定义 maximum 变量,使其成为局部变量,然后您尝试在其定义块之外访问该变量的值,这就是 Java 找不到此类变量的原因,因为它不存在于该范围内。试试这个:

public class Test {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("Enter a list of integers: ");
        int array[] = new int[10];
        int maximum = 0;
        for (int i = 0; i < array.length; i++) {
            array[i] = s.nextInt();
        }

        for (int j = 0; j < array.length; j++) {
            if (j < array.length) {
                maximum = Math.max(array[j], array[j + 1]);
            }
        }

        System.out.println("Largest number of the list: " + maximum);
    }
}

尝试阅读此链接以获取有关范围和变量的进一步说明。

© www.soinside.com 2019 - 2024. All rights reserved.