如何修复我在main方法上显示的方法?

时间:2014-11-29 04:15:16

标签: java

public class Hw7Pr2 {

    public static void main(String[] args) {
        int [] grades={40,55,70,58};

        System.out.println("best: ");
        int[] best1 = best(grades);

        for (int i = 0; i < best1.length; i++) {
            System.out.print(best1[i]);
        }
    }   

    public static int[] best(int[] grades){
        System.out.println("The best scores is: ");
        int best = grades[0];
        for (int i = 0; i < grades.length; i++) {
            if (grades[i] > best)
                best = grades[i];
            return best;
        }
    }
}

我的方法不能按照我需要的方式工作。我收到了这个错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Type mismatch: cannot convert from int to int[]

2 个答案:

答案 0 :(得分:1)

int[] best1 = best(grades);

在这里,你试图得到一个单一的数字,最高分。为此,您不需要一个int数组,只需要一个int。它应该是

int best1 = best(grades);

由于您只有1个号码,因此您在打印后也不需要使用for循环,只需打印您现有的单个int。

System.out.print(best1);

您的方法的逻辑看起来很好,但您的返回类型不正确。您的方法找到单个最大数字,这意味着您不需要在那里返回一个数组,只需要一个int。

public static int[] best(int[] grades)

变为

public static int best(int[] grades)

此外,看起来你的return语句在你的方法中的for循环中。您希望在方法之外,只有在检查整个数组后才返回。所有代码都将如下所示

public class Hw7Pr2 {

    public static void main(String[] args) {
        int [] grades = {40, 55, 70, 58};        

        System.out.print("Best: ");
        int best1 = best(grades);
        System.out.print(best1);
    }

    public static int best(int[] grades){
        if (grades == null || grades.length < 1) { return -1; } //Should always check

        int best = grades[0];
        for (int i = 1; i < grades.length; i++) {
            if (grades[i] > best) {
                best = grades[i];
            }
        }
        return best;
    }
}

答案 1 :(得分:0)

首先,您的方法best对我来说听起来像max。你似乎错过了一个大括号(我建议你总是使用大括号)。您也可以将其设为variadac function。像

这样的东西
public static int max(int... values) {
    if (values == null || values.length < 1) { // <-- check for null.
        return -1;
    }
    int max = values[0];
    for (int i = 1; i < values.length; i++) { // <-- I'd start at 1 (not 0)
        if (values[i] > max) { // <-- braces
            max = values[i];
        }
    }
    return max;
}

然后您可以调用它,并使用Arrays.toString(int[])打印您的数组,例如

public static void main(String[] args) {
    int[] grades = { 40, 55, 70, 58 };
    System.out.printf("Best: %d%n", max(grades)); // <-- or, max(40,55,70,58)
    System.out.println(Arrays.toString(grades));
}

输出

Best: 70
[40, 55, 70, 58]