2

I have made a small Java program that calculates the percentage for a student's exam. I just started programming in Java yesterday, so I got into a little trouble with a bug. Here is the code:

public class Userinput {
public static void main(String[] args) {
    System.out.println("Hi dear Student. This is a percentage calculator.");
    Scanner sc = new Scanner(System.in);
    System.out.println("How many Subjects do you have?");
    int totalSubjects = sc.nextInt();
    System.out.println("Out of how many marks did you have your exams/tests?");
    int outOf = sc.nextInt();

    int actualOutof = outOf;
    int markSubjects1 = 0;
    int markSubjects2 = 0;
    int markSubjects3 = 0;
    int markSubjects4 = 0;
    int markSubjects5 = 0;
    int markSubjects6 = 0;
    int markSubjects7 = 0;
    int markSubjects8 = 0;
    int markSubjects9 = 0;
    int markSubjects10 = 0;
    int i = 0;
    int totalSubjectsActual = totalSubjects + 1;

    for (i=1; i<totalSubjectsActual; i++) {
        System.out.println("How many marks did you score in the next subject?");

        if (i == 1) {
            markSubjects1 = sc.nextInt();
        } else if (i == 2) {
            markSubjects2 = sc.nextInt();
        } else if (i == 3) {
            markSubjects3 = sc.nextInt();
        } else if (i == 4) {
            markSubjects4 = sc.nextInt();
        } else if (i == 5) {
            markSubjects5 = sc.nextInt();
        } else if (i == 6) {
            markSubjects6 = sc.nextInt();
        } else if (i == 7) {
            markSubjects7 = sc.nextInt();
        } else if (i == 8) {
            markSubjects8 = sc.nextInt();
        } else if (i == 9) {
            markSubjects9 = sc.nextInt();
        } else if (i == 10) {
            markSubjects10 = sc.nextInt();
        }
    }
    int outOfMarks = actualOutof*totalSubjectsActual;
    int startAverage = markSubjects1 + markSubjects2 + markSubjects3 + markSubjects4 + markSubjects5 + markSubjects6 + markSubjects7 + markSubjects8;
    int decimalMarks = startAverage/outOfMarks;
    int average = decimalMarks*100;

    System.out.println("Average Percentage for all Subjects: " + average + "%");
}};

All of the code is working well, except for the last part. When I try to calculate the percentage from the result, it shows either 0 or 100. Please help me regarding this...

Soham Grover
  • 121
  • 6

1 Answers1

1

The reason is, that you are using int to calculate the precentage.

Change your last four variables from int to double or float.

Int can't show you decimals. If you have for example 0.24 as a value it will cut .24 away and will only show you 0

There are a few other things that you can use to optimize your programm. Try looking into Arrays.