gpt4 book ai didi

Java:查找数组中 double 的平均值

转载 作者:行者123 更新时间:2023-12-01 11:01:00 24 4
gpt4 key购买 nike

我正在为我的 Java 入门类(class)做作业。作业的一部分是将文本文件中的 double 读入数组,然后使用不同的方法计算平均值。到目前为止,我已将 double 读入数组,但我不确定如何在另一种方法中引用该数组来计算平均值。我一直在网上搜索,但没有结果,可能是因为我糟糕的术语导致我得到不相关的答案。我从 netbeans 收到一个错误,指出无法找到符号 classGrades(因为它仅在 main 方法中。)我尝试将其定义为全局变量,但这不起作用,我们还没有了解这些,所以一定有另一种方法可以做到这一点。

总结一下:我不知道如何在方法之间引用变量。

这是我的代码

import java.io.File;
import java.util.Arrays;
import java.util.Scanner;

public class GradeChecker {

public static void main(String[] args) {
// TODO code application logic here
double[] classGrades = new double[76];
double classAverage = calculateAverageGrade();


fillArray(classGrades);
for (int i = 0; i < classGrades.length; i++) {
System.out.println(classGrades[i]);
}
//System.out.print(Arrays.toString(classGrades));
System.out.print(classGrades.length);

}
public static void fillArray(double[] ary) {
try {
File arrayInput = new File("ClassGrades.txt");
Scanner in = new Scanner(arrayInput);
in.useDelimiter("\r\n");

int i = 0;
while (in.hasNextLine()) {
ary[i++] = in.nextDouble();
}
in.close();
} catch (Exception exception) {
System.out.println("Error: " + exception.getMessage());
}
}

private static double calculateAverageGrade(double[] classGrades) {
double gradeSum = 0;
double gradeAverage = 0;
for (int i = 0.0; i < classGrades.length; i++) {
gradeSum = gradeSum + classGrades[i];
}
gradeAverage = gradeSum/classGrades.length;
return gradeAverage;
}
}

最佳答案

您可以将数组 classGrades 传递给函数:

    double[] classGrades = new double[76];
double classAverage = calculateAverageGrade(classGrades);

这里:

import java.io.File;
import java.util.Arrays;
import java.util.Scanner;

public class GradeChecker {

public static void main(String[] args) {
// TODO code application logic here
double[] classGrades = new double[76];
double classAverage = calculateAverageGrade(classGrades);


fillArray(classGrades);
for (int i = 0; i < classGrades.length; i++) {
System.out.println(classGrades[i]);
}
//System.out.print(Arrays.toString(classGrades));
System.out.print(classGrades.length);

}

public static void fillArray(double[] ary) {
try {
File arrayInput = new File("ClassGrades.txt");
Scanner in = new Scanner(arrayInput);
in.useDelimiter("\r\n");

int i = 0;
while (in.hasNextLine()) {
ary[i++] = in.nextDouble();
}
in.close();
} catch (Exception exception) {
System.out.println("Error: " + exception.getMessage());
}
}

private static double calculateAverageGrade(double[] classGrades) {
double gradeSum = 0;
double gradeAverage = 0;
for (int i = 0; i < classGrades.length; i++) {
gradeSum = gradeSum + classGrades[i];
}
gradeAverage = gradeSum / classGrades.length;
return gradeAverage;
}
}

关于Java:查找数组中 double 的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33322740/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com