简体   繁体   English

从数组中读取并计算平均值

[英]Read from array and calculate average

I am trying to write code that reads a row of characters from an array, assign the characters to an integer and then average all the integers of the row, it does this for every row in the array. 我正在尝试编写代码,以从数组中读取一行字符,将这些字符分配给一个整数,然后平均该行的所有整数,它对数组中的每一行都执行此操作。 Here is what I have so far : 这是我到目前为止所拥有的:

Scanner in = new Scanner(new File("Grades.txt"));

while(in.hasNextLine()) {
    int gp = 0;
    double gpa = 0;
    String line = in.nextLine();

    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;
    }
    }

    gpa = gp / letters.length;

    System.out.println(gpa);
}

Here is the array that i am working with : 这是我正在使用的数组:

[, D, D, C, P, H, H, C]
[, H, H, H, D, D, H, H]
[, C, F, C, D, C, C, C]
[, F, F, F, P, C, C, C]
[, F, C, F, C, D, P, D]
[, D, D, F, D, D, F, D]
[, P, F, P, F, P, F, P]

Here is the current output of the code : 这是代码的当前输出:

5.0
6.0
3.0
2.0
3.0
4.0
2.0

Contents of the text file : 文本文件的内容:

45721 Chris Jones D D C P H H C D
87946 Jack Aaron H H H D D H H H
43285 Ben Adams C F C D C C C P
24679 Chuck Doherty F F F P C C C F
57652 Dean Betts F C F C D P D H
67842 Britney Dowling D D F D D F D D
22548 Kennedy Blake P F P F P F P P

Am I on the right path? 我在正确的道路上吗? would there be an easier method? 有没有更简单的方法? Any help would be greatly appreciated. 任何帮助将不胜感激。

Just a quick note to save you some grief later 只是一个简短的注释,以免您以后感到悲伤

Shouldn't 不能

line = line.substring(line.length()-16, line.length()-1);

be instead 代替

line = line.substring(line.length()-15, line.length());

to get all the grades? 获得所有成绩?

And then you'll need to put your if statements into a for loop, that loops over each value of the array (replace the letters[1] with letters[i] ) 然后,您需要将if语句放入for循环中,该循环遍历数组的每个值(将letters[1]替换为letters[i]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM