为什么我要在main内部调用的方法不起作用?

时间:2018-11-09 02:08:32

标签: java

# Display the average of each student's grade. # Display tthe average for each assignment. gradebook = [61, 74, 69, 62, 72, 66, 73, 65, 60, 63, 69, 63, 62, 61, 64], [73, 80, 78, 76, 76, 79, 75, 73, 76, 74, 77, 79, 76, 78, 72], [90, 92, 93, 92, 88, 93, 90, 95, 100, 99, 100, 91, 95, 99, 96], [96, 89, 94, 88, 100, 96, 93, 92, 94, 98, 90, 90, 92, 91, 94], [76, 76, 82, 78, 82, 76, 84, 82, 80, 82, 76, 86, 82, 84, 78], [93, 92, 89, 84, 91, 86, 84, 90, 95, 86, 88, 95, 88, 84, 89], [63, 66, 55, 67, 66, 68, 66, 56, 55, 62, 59, 67, 60, 70, 67], [86, 92, 93, 88, 90, 90, 91, 94, 90, 86, 93, 89, 94, 94, 92], [89, 80, 81, 89, 86, 86, 85, 80, 79, 90, 83, 85, 90, 79, 80], [99, 73, 86, 77, 87, 99, 71, 96, 81, 83, 71, 75, 91, 74, 72]] #make variable for assingment averages #make a variable for student averages stu_avg = [sum(row)/len(row) for row in gradebook] print(stu_avg) #Assignment Class class Assignment: def __init__(self, name, average): self.average = average self.name = name def print_grade(self): print("Assignment", self.name, ":", self.average) #Student Class class Student: def __init__(self, name, average): self.average = average self.name = name def print_grade(self): print("Student", self.name, ":", self.average) s1 = Student("1", stu_avg[0]) s2 = Student("2", stu_avg[1]) s3 = Student("3", stu_avg[2]) s4 = Student("4", stu_avg[3]) s5 = Student("5", stu_avg[4]) s6 = Student("6", stu_avg[5]) s7 = Student("7", stu_avg[6]) s8 = Student("8", stu_avg[7]) s9 = Student("9", stu_avg[8]) s10 = Student("10", stu_avg[9]) s1.print_grade() s2.print_grade() s3.print_grade() s4.print_grade() s5.print_grade() s6.print_grade() s7.print_grade() s8.print_grade() s9.print_grade() s10.print_grade() 无法识别。我不知道我做错了什么,但是我确信这是一个非常简单的修复。尝试找出与所使用的数据类型有关,还是与添加的行“”有关。有提示吗?

minGap(array);

1 个答案:

答案 0 :(得分:0)

我相信您想要一种找到最小间隙的方法。因此,您不应该将该传入方法。您的逻辑也有些偏离,您想在gapMin>gap[i]之后取最小值(而不是硬编码的gap[1])。所以你可以做,

private static int minGap(int a[]) {
    int gapMin = Integer.MAX_VALUE;
    int[] gap = new int[a.length];
    for (int i = 0; i < a.length; i++) {
        if (gapMin > gap[i]) {
            gapMin = gap[i];
        }
    }
    return gapMin;
}

(如果您使用的是Java 8 +)

private static int minGap(int a[]) {
    return Arrays.stream(a).min().getAsInt();
}

然后,您需要实际保存该值或print。也就是说,改变

minGap(array);

(仅打印)

System.out.println(minGap(array));

并且,您需要一个int(而不是String[])数组。

int[] array = new int[length];
for(int i = 0; i < length; i++) {
    System.out.printf("Please enter integer %d for the array%n", i + 1);
    array[i] = input.nextInt();
}