我有一些代码从数组中读取一行字符,将这些字符分配给一个整数,然后对该行的所有整数求平均值,它对数组中的每一行执行此操作。由于我是java新手,我在尝试将每行的平均值(gpa)存储在另一个数组中时遇到了麻烦。这是我到目前为止所拥有的:
Scanner in = new Scanner(new File("Grades.txt"));
Scanner in2 = new Scanner(new File("Grades.txt"));
int size = 0;
while(in2.hasNextLine()) {
size++;
}
int count = 0;
double [] gpalist = new double[size] ;
while(in.hasNextLine()) {
size++;
double gp = 0;
double gpa = 0;
String line = in.nextLine();
double [] arraygpa = new double [7];
if(line.length() == 0) {
continue;
}
line = line.substring(line.length()-15, line.length());
String[] letters = line.split(" ");
for (int i = 0; i < letters.length; i++) {
if (letters[i].equals("H")) {
gp += 7;
}
else if (letters[i].equals("D")) {
gp += 6;
}
else if (letters[i].equals("C")) {
gp += 5;
}
else if (letters[i].equals("P")) {
gp += 4;
}
else if (letters[i].equals("F")) {
gp += 0;
}
}
gpalist[count++] = gp / letters.length;
System.out.println(Arrays.toString(gpalist));
}
这是当前输出:
[5.75]
[6.75, 0.0]
[4.375, 0.0, 0.0]
[2.375, 0.0, 0.0, 0.0]
[4.125, 0.0, 0.0, 0.0, 0.0]
[4.5, 0.0, 0.0, 0.0, 0.0, 0.0]
[2.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
我试图将平均值(gpa)存储在另一个数组中,但我的尝试远远不正确。不幸的是,禁止使用 ArrayLists 作为解决方案。如果有人能指出我正确的方向,我将不胜感激。
最佳答案
由于您可能事先不知道等级数,因此这是 ArrayList 的一个很好的用例。 。
List<Double> gpas = new ArrayList<Double>();
while(in.hasNextLine()) {
int gp = 0;
double gpa = 0;
...
gpa = gp / letters.length;
gpas.add(gpa);
...
} // End while
如果您稍后需要一个“简单”数组,ArrayList 类有几个 toArray 方法。
更新:
如果每个学生有 8 个成绩,您可以预先初始化该大小的数组,并在 while 循环外部保留一个索引变量:
double[] gpas = new double[8];
int index = 0;
while(in.hasNextLine()) {
int gp = 0;
double gpa = 0;
...
gpas[index] = gp / letters.length;
index++;
...
} // End while
关于java - 将变量存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26294257/