user2157247 - 6 months ago 39

Java Question

I made a simple grade system for fun. I'm trying to apply the total of grades and add it to an equation in my

`getApercent()`

`package gradesystem;`

import java.util.Scanner;

public class Gradesystem {

public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);

Gradesystem gs = new Gradesystem();

// TODO Auto-generated method stub

int Acount,Bcount,Ccount,Dcount,Fcount;

double ap,bp,cp,dp,fp;

System.out.println("Enter the amount of A's");

Acount = keyboard.nextInt();

System.out.println("Enter the amount of B's");

Bcount = keyboard.nextInt();

System.out.println("Enter the amount of C's");

Ccount = keyboard.nextInt();

System.out.println("Enter the amount of D's");

Dcount = keyboard.nextInt();

System.out.println("Enter the amount of F's");

Fcount = keyboard.nextInt();

int grades;

ap = getApercent(Acount);

System.out.println(ap);

bp = getBpercent(Bcount);

System.out.println(bp);

cp = getCpercent(Ccount);

System.out.println(cp);

dp = getDpercent(Dcount);

System.out.println(dp);

fp = getFpercent(Fcount);

System.out.println(fp);

}

public static void Totalgrades(int acount, int bcount, int ccount, int dcount, int fcount){

int totalofgrades = acount + bcount + ccount + dcount + fcount;

System.out.print(totalofgrades);

}

public static double getApercent(int a){

double ap;

ap = (a/a * 100) + 0.5;

return Math.round(ap);

}

public static double getBpercent(int b){

double bp;

bp = (b/b * 100) + 0.5;

return Math.round(bp);

}

public static double getCpercent(int c){

double cp;

cp = (c/c * 100) + 0.5;

return Math.round(cp);

}

public static double getDpercent(int d){

double dp;

dp = (d/d * 100) + 0.5;

return dp;

}

public static double getFpercent(int f){

double fp;

fp = (f/f * 100) + 0.5;

return fp;

}

}

Answer

A little bit of guessing here. But the methods that calculate the percentage seem off. Again, assuming; but to calculate the percentage of a whole you would use the following formula `percentage = part/whole * 100`

e.g.

we have 9 grades and 3 are A's, 3 are B's, 2 are C's, 1 is D's, and 0 are E's.

Then I'd expect the percentages to be as follows:

```
33% A // 3 / 9 * 100
33% B // 3 / 9 * 100
22% C // 2 / 9 * 100
11% D // 1 / 9 * 100
0% E // 0 / 9 * 100
```

One other thing to point out is the the operator `/`

with two ints does integer division. So `3 / 9 == 0`

.

You could replace all the specific methods with a more generic version.

```
public static double getPercentage(int gradeCount, int totalNumberOfGrades) {
double percentage = ( gradeCount / (double) totalNumberOfGrades * 100);
return Math.round(percentage);
}
```

Source (Stackoverflow)