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.
CodePudding user response:
Problem is with the input array datatype. If input array is also expecting double value (with decimal) you need to take the input array as double.
Please change the below line
int[] input = new int[length];
with
double[] input = new double[length];
and below line
input[i] = adnan.nextInt();
with
input[i] = adnan.nextDouble();
It will work for both the types of numbers(with and without decimal).
I hope this will solve the issue you're facing.
CodePudding user response:
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;
}
CodePudding user response:
In java if both are int, result is also int. So you can use sum / Double.valueOf(input.length);