AJJ
AJJ

Reputation: 897

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.

Upvotes: 0

Views: 95

Answers (1)

Andrew Alderson
Andrew Alderson

Reputation: 903

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])

Upvotes: 1

Related Questions