Ian - 5 months ago 17

Java Question

`public class apples {`

private static String[] level1 = new String[] { "A", "B", "I", "K", "N", "O", "P", "S", "T", "W" };

public static void main(String[] args) {

int[] scores1 = { 99, 80, 56, 88, 70, 35, 67, 60, 78, 56 };

int[] correct1 = {20, 20, 13, 15, 22, 18, 19, 21, 23, 25};

int[] incorrect1 = {2, 1, 5, 2, 2, 5, 8, 1, 0, 0};

double[] percentage1 = new double[correct1.length];

for(int a = 0; a < correct1.length; a++ ){

percentage1[a] = (double)((correct1[a] / (correct1[a] + incorrect1[a]))*100);

}

System.out.println("Character \t Correct \t Incorrect \t Percentage");

for(int counter = 0; counter<scores1.length;counter++){

System.out.println(level1[counter] + "\t\t " + correct1[counter] + "\t\t " + incorrect1[counter] + "\t\t " + percentage1[counter]);

}

}

}

This outputs a table with 4 headings. The character, correct and incorrect columns show as expected. However the percentage row is not working properly. For example, character 'A', correct 20 and incorrect 2 gives a percentage of 0.0. Any 'incorrect' value > 0 outputs a percentage value of 0, and any 'incorrect' value which = 0 gives a percentage value of 100 (which is correct)... Can someone please explain where I have gone wrong?

Answer

You are dealing with integers here, and for integer division, the result is truncated. You'll need to cast the original values to double instead, or multiply one part by `1.0`

to get it as a double:

```
percentage1[a] = ((correct1[a]*1.0 / (correct1[a] + incorrect1[a]))*100);
```