Java: Calculating average GPA with intArr of 12 students - java

I'm trying to write a script to calculate the average GPA of the class and which shows the lowest and highest grades achieved by the students.
I'm trying how to get the average of the 12 numbers. I know I need to add all the number and divide them 12. Can someone give me a few tips on how I can do this. Thansk!!

If you are using Java 8 there are good facilities for stats:
IntSummaryStatistics stats = Arrays.stream(grades).summaryStatistics();
Then you can use stats.getMin, stats.getAverage etc.
If, on the other hand, this is a homework assignment then you probably should write your own code to do this rather than use the Java library.

Suppose the 12 students have the grades in the array intArr
public int calculateAverage(){
int[] intArr = {1,2,3,4,5,6,7,8,9,10,11,12};
//Total number of students grades in the array
int totalStudents = intArr.length;
//Variable to keep the sum
int sum = 0;
for (int i = 0; i < totalStudents; i++){
sum = sum + intArr[i];//Add all the grades together
}
int average = sum/totalStudents;
return average;
}

What #SiKing said, what code have you tried? Show us what you've coded!
#nitinkc's code is on the right track although not completely correct by OO standards.
Here's what I have. This is just a function. You must implement your runner yourself assuming you have just a main runner class...
// initialise and pass in your array into your function
public static double calculateAverage(int[] array) {
// double because averages are more than likely to have decimals
double gradesTotal = 0;
// loop through each item in your array to get the sum
for(int i = 0; i < array.length; i++) {
gradesTotal = gradesTotal + array[i];
}
// return the sum divided by number of grades
return gradesTotal/array.length;
}

Related

Averaging Items in an Array, in an Array

I want to loop through my array list roster and for each Student item I want to return the average of an array of grades. I know there are 3 grades so this code works, but how can I implement this if I don't know how many grades are in the Student's grades array before hand?
public static void printAverageGrades(){
System.out.println("Print Average Grades");
for(Student item : roster)
{
double div = roster.size();
**double average = (item.getGrades()[0] + item.getGrades()[1] + item.getGrades()[2]) / div;**
System.out.printf("%.2f \n", average);
}
}
You can do this two ways. The more preferable Java 8 way is listed first.
Use Arrays.stream to encapsulate the array as a stream, then getting the average is just a couple of method calls away.
double avg = Arrays.stream(item.getGrades()).average().getAsDouble();
Use another for loop and keep a running total of the elements. Don't forget to manually coerce your numerator to a double or you'll run into integer division.
int sum = 0;
for(int i : item.getGrades()) {
sum += i;
}
double avg = (sum * 1.0) / item.getGrades().length;
In practice, never hard-code your index locations. You can always get the length of an array using .length.
You can just use this function, in which would iterate through the array, by dynamically iterating through for loop, we compute sum.
Then average would be divided by the length of array.
double getAverage(double[] data)
{
double sum = 0.0;
for(double a : data)
sum += a;
return sum/data.length;
}

How to extract numbers from an array list, add them up and divide by the amount of numbers in the array list?

I was watching a lesson online about arrays. It taught me the 'basics' of array lists: how to create an array list. So I was wondering, how would one go about creating an array list from the users' input (JOptionPane), extract the numbers out of it, add them up and divide by the total amount of numbers in the array list (long story short, calculate the average of the array)?
Here's my, somewhat of an approach:
import java.util.Arrays;
import javax.swing.JOptionPane;
public class JOptionPaneTesting {
public static void main(String[] args){
int grades = Integer.parseInt(JOptionPane.showInputDialog("What are your grades of this month?"));
int arrayList[] = {Integer.valueOf(grades)};
int arraysum;
arraysum = arrayListGetFirstIndex + arrayListGetSecondIndex + ...; //Extracts all of the indices and adds them up?
int calculation;
calculation = arraysum / arrayListAmmountOfNumbersInTheList; //An example of how it go about working
}
}
As far as i understand the question, you are trying to get input from user. The input is the grades. Then you wanted to add up the grades and calculate the average of the grades.
public static double calculateAvg(List<Double>inputGrades){
List<Double> grades = new ArrayList<Double>(inputGrades);
double totalScore = 0.0;
double avgScore = 0.0;
if(grades !=null && grades.size()>0){
for(Double grade : grades){
totalScore = totalScore + grade;
}
avgScore = totalScore / grades.size();
}
return avgScore;
}
Taking user input and adding it to the list
List<Double> gradesList= new ArrayList<Double>();
gradesList.add(25.5);
gradesList.add(29.5);
gradesList.add(30.5);
gradesList.add(35.5);
System.out.println(calculateAvg(gradesList));
This would be a suitable solution too:
String[] input = JOptionPane.showInputDialog("What are your grades of this month?").split(" ");
double[] grades = new double[input.length];
double average = 0.0;
for (int i = 0; i < input.length; i++) {
// Note that this is assuming valid input
grades[i] = Double.parseDouble(input[i]);
average+=grades[i];
}
average /= grades.length;
So you could type in multiple "grades" seperated by a whitespace.
first create a list
List<Integer> list = new ArrayList<Integer>();`
then list.add(grade);
you need iterate whole above line if you want add more than one grades.
then list.get(index) get you specific (index) grade.
to calculate arraySum use :
for(int i = 0; i < list.size() ; i++)
arraysum += list.get(i); // and others are same.
I hope this helps you!

Making a method for an array

I have an array that takes student grades from an input. I have to make a method that will find the average of the numbers within the array. Here is the code i have so far...
int mark = Integer.parseInt(input.getText());
if(mark <= 100){
marks.add(Integer.parseInt(input.getText()));
input.setText("");
warningLbl.setText("");
}
else{
warningLbl.setText("Please enter an number between 0-100");
}
I want to take the contents in the array 'marks' and get an average for them then append it in my text area
public static double getAverage(int[] marks)
{
int sum = 0;
for(int i : marks) sum += i;
return ((double) sum)/marks.length;
}
This is the method i have to find the average, but i dont know how to use this method and get it to print in a text area
If you want to find the average stored in an array , try the following function.
public static double average(int[] marks)
{
int sum = 0;
double average;
for(int element: marks)
{
sum = sum + element;
}
average = (double)sum / marks.length;
return average;
}
Hope it helps ! :)
The above method is used to find average in an array(primitive type) , but to find average in List type array(wrapper class) , we have to iterate through each element in the list by this way and do the required calculations :
public static String average(Integer[] marks)
{
int sum = 0;
double average;
for (int i = 0; i < marks.size(); i++)
{
sum = sum + marks.get(i);
}
average = (double) sum / marks.size();
String averageString = Double.toString(average);
return averageString;
}
This returns your average in string type directly.
There are several problems with your current code.
Using input.getText(); twice will mean it's going to prompt for input twice. Have a single line like int mark = Integer.parseInt(input.getText()); then use the mark variable wherever it's needed.
In order to test if the number is between 0 and 100 (I'm assuming this needs to be inclusive), that if statement would need to be (mark >= 0 && mark <= 100).
I assume you want to get multiple students' grades/marks, so it may be a good idea to enclose your code in a for or while loop, depending on how you want it to operate. However, since this will be of variable length I'd recommend using a List over an array for resizing.
Finding the average is easy. Just use a foreach loop to sum up all the numbers, then divide that by the array length.

Why wont my array average all numbers?

i have to create an array and a method call for the average. but for some reason it is not average all numbers, its only returning the last number. I have asked my instructor for help and she said the math is correct it should work. But no other help from her. What have I done wrong?
public static void main(String[] args) {
double[] myArray = new double[2];
initialize(myArray);
double avg = getAverage(myArray);
System.out.println(avg);
output(avg);
}
public static void initialize(double[] myArray) {
//myArray = new double[1000];
for(int i = 0; i < myArray.length; i++) {
myArray[i] = (int) ((Math.random()*500)*1);
System.out.println(myArray[i]);
}
}
/**
*
* #param myArray
* #return
*/
public static double getAverage(double[] myArray) {
int sum = 0;
for (int i = 0; i < myArray.length; i++) {
sum += myArray[i];
}
return sum / myArray.length;
}
public static void output(double avg) {
System.out.println("The average is " + avg);
}
The key is in this line:
sum / myArray.length
...since both sum and myArray.length are integers, Java performs integer division, not floating point division, which essentially means it drops the decimal component of the result.
Casting one of the values to a double first will force a floating point division to occur.
You're also storing the sum as an int, which could again introduce a source of error since the array contains doubles. In this case you're ok because you're casting everything you put into the array to an int first, which begs the question as to why you're using a double array in the first place?
As an aside, this is a bit odd:
((Math.random()*500)*1);
There's no need to multiply the result by 1 here - that won't do anything.
What is the problem here? The answers are coming correctly. Please check again. The interesting fact is that the third number is always same as the average of all three. But the average computation is correct. That may be how Math.random() generates random numbers internally. The third is the average of the other two. Try out four or five numbers instead of three numbers and check your answers.

Java calculating average of numbers from another file

public void computeAverage(String [] names, int [] scores, char [] grades){
int av = 0;
for (int i = 0; i < names.length; i++)
av = (scores[i]++ / 26);
System.out.print(av);
}
Hey guys,
Above is my code to read a list of test scores and compute their average. There are 26 test scores. I am having trouble, Please help!
Thanks
The problem here is that you keep writing over the av variable during each iteration of the loop. Also, it looks like you don't needs the names and grades arrays as parameters, as you're not using them. This should work better:
public void computeAverage(int [] scores)
{
double average = 0;
for (int i = 0; i < scores.length; i++)
{
average += scores[i];
}
average /= scores.length;
System.out.print(average);
}
Let's break this down:
You need to loop through your entires scores array and sum each score
to a running total
You need to then divide by total number of scores. As #cliff.meyers
pointed out, that is the definition of an average
As a side note, you are looping against name.length, but indexing
into scores. That is bad.
You are dividing by a hard coded constant. That is also bad.
You don't need names or grades in the function to calculate averages.
Try adding them all first, then dividing by the total number. That's how you calculate an average...
You need to add the contributions to the running tally:
av += (scores[i] / 26.0);
Perhaps even better to divide by names.length, and even better to leave the division to the end. Finally, be careful with integer division, which might not do what you think it does.
public static int computAverage(int[] scores)
{
long sum = 0;
for(int i : scores)
sum += i;
return sum / scores.length;
}

Categories

Resources