对于我的作业,我正在让一个程序读取一个文本文件,该文件有一堆整数值,表示特定课程某一部分的学生数量。使用此文本文件,我需要找到学生的平均值,部分的最小值和最大值。
现在作业的细节并不清楚,但我想做的是:
在main方法中建立一些变量和数组,以及调用方法来执行计算然后返回值,以便main方法可以打印。
我被困在将每个值加在一起的部分(所以我可以用它来计算平均值)
我的整体问题是,如何将文本文件中的值一起添加?
一种子问题是我必须让扫描仪类读取每种方法中的文本文件吗?
我希望我提出的问题是有道理的,并且会对任何澄清给予感激:)
import java.util.Scanner;
public class EnrollmentStats
{
public static void main(String[] args) throws Exception
{
// Create array to hold enrollments
double[] enrollment = new double [100];
// decale int for number of elements actually used
int count;
// call method to read data into enrollment[] line by line and return count
count = readLines(enrollment);
// call method to calculate average class size
sectionAvg (enrollment);
// call method to calculate minimum class size
sectionMin(enrollment);
// call method to calculate max class size
sectionMax(enrollment);
// print results (count, average size, min size, and max size)
System.out.println();
} // End main ()
// This method reads data from the file into the array and returns the number
// of elements it uses
public static int readLines(double[] line ) throws Exception
{
int count = 0;
java.io.File sections = new java.io.File("enrollment.txt");
Scanner infile = new Scanner(sections);
while( infile.hasNextLine() )
{
line[count] = infile.nextDouble();
count ++;
System.out.println(" count is" + count);
} // End while
return count;
} // end readlines
public static double sectionAvg (double[] registered ) throws Exception
{
return avg;
}
答案 0 :(得分:0)
将这些放在main
方法之外
// method to read data into enrollment[] line by line and return count
readLines(double[] enrollment) {
// do something
}
// method to calculate average class size
sectionAvg (double []enrollment) {
// do something
}
// method to calculate minimum class size
sectionMin(double[] enrollment) {
// do something
}
// method to calculate max class size
sectionMax(double[] enrollment) {
// do something
}
尝试并实施上述方法。 提示:方法签名不完整。您需要一个返回类型。然后像您一样调用main
中的方法
count = readLines(enrollment);
在你来之前先尝试解决并寻求帮助。 Mkae你的问题具体表明你已经做了一个诚实的尝试,但你有一些具体和可解释的问题
答案 1 :(得分:0)
检查一下......
我将这些值放在文本文件prog2test.txt中作为
1
2
3
4
5
代码:
import java.io.File;
import java.util.Scanner;
public class Prog2
{
public static void main(String args[]) throws Exception
{
Scanner in = new Scanner(new File("prog2test.txt"));
int sum = 0;
while(in.hasNextInt()){
sum = sum + (in.nextInt());
}
System.out.println(sum);
}
}