Skip to content
Advertisement

data type and calculate average in java

I am working on a java code that calculates the average of grades in an array for N of students and it is working fine when I enter grades like {3,4,3} but when I use numbers with decimals like {3.7,2.5,3.2} it starts giving me errors and I want to make a class of data type Students for example.

import java.util.*;
public class ArrayAverageProblem { 
   public static void main(String[] args) { 
      System.out.println("Enetr number of students : "); 
      Scanner adnan = new Scanner(System.in); 
      int length = adnan.nextInt(); 
      int[] input = new int[length]; 
      System.out.println("Enter cgpa of students : "); 
      for (int i = 0; i < length; i++) { 
         input[i] = adnan.nextInt(); 
      } 
      double averageCgpa = averageCgpa(input); 
      System.out.println("Average of students cgpa :  " + averageCgpa); 
      adnan.close(); 
   }   
   public static double averageCgpa(int[] input) { 
      double sum = 0f; 
      for (int number : input) { 
         sum = sum + number; 
      } 
      return sum / input.length; 
   } 
}

Any help would be really appreciated.

Advertisement

Answer

i improved your code to use double numbers. note that your grades must be double and use nextDouble() method to get grade from scanner. this code is below

public static void main(String[] args) {

    System.out.println("Enetr number of students : ");

    Scanner adnan = new Scanner(System.in);

    int length = adnan.nextInt();

    double[] input = new double[length];

    System.out.println("Enter cgpa of students : ");

    for (int i = 0; i < length; i++) {

        input[i] = adnan.nextDouble();

    }

    double averageCgpa = averageCgpa(input);

    System.out.println("Average of students cgpa :  " + averageCgpa);

    adnan.close();

}



public static double averageCgpa(double[] input) {

    double sum = 0f;

    for (double number : input) {

        sum = sum + number;

    }

    return sum / input.length;

}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement