3

I can't seem to get my percentages to display properly. It is always showing 0.0 every time it loops. Everything else in the code seems to work.

I've probably missed something obvious but I'm a bit of a noob when it comes to Java so any help is greatly appreciated.

package e2E3;
import java.util.Scanner;

public class Main {

    public static void calculatePercentage(int studentMark, int maxMark){
        double percentage;
        percentage = studentMark / maxMark * 100;
        System.out.println("%" + percentage);

    }

    public static void totalAndAverageMark(){

            Scanner userInput = new Scanner(System.in);
            int numberOfStudents = 0;
            int maxMark = 0;
            int totalMark = 0;
            int studentCount = 0;
            int studentMark = 0;
            int average = 0;

            System.out.println("how many Students Sat the Test?");
            numberOfStudents = userInput.nextInt();

            System.out.println("what is the Maximum score?");
            maxMark = userInput.nextInt();

            do {

                System.out.println("enter students score..");
                studentMark = userInput.nextInt();

                calculatePercentage(studentMark, maxMark);

                totalMark = totalMark + studentMark;

                studentCount = studentCount + 1;

            } while (studentCount != numberOfStudents);

            average = totalMark / numberOfStudents;
            System.out.println("The Average Grade of Students was.. " + average);   

    }

    public static void main(String[] args) {

        totalAndAverageMark();

    }

}
River
  • 8,585
  • 14
  • 54
  • 67
bodovix
  • 299
  • 2
  • 4
  • 11

1 Answers1

2

You are dividing integers and as such the result is always an integer value. You can declare studentMark as double and it will work as expected. If you don't want this, you can cast it to double in the division (double) studentMark / maxMark * 100;

Slimu
  • 2,301
  • 1
  • 22
  • 28