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;
}
Related
I'm new to Java and I'm stuck on this problem:
"Create a second add() method which has a single parameter of an array of doubles and, inside the method, adds the values of the array, returning the result as a double. Sample test data:
double[] dblArr = {11.82,88.23,33};
I have a separate class file with the following so far:
public double add(double[] values) {
int sum = 0;
for (double i : values)
sum += i;
return sum;
}
This is the method to add the array's and return the total sum.
And this is the code I have in my "main" document to call the method
double dblArr;
utils.print("Please enter an array of 5 numbers: ");
dblArr = input.nextDouble();
double sum = calc.add(dblArr);
System.out.println(dblArr);
I know I'm quite off scope so some advice would be really appreciated, thank you
"calc" is what I'm using to call the other document
Calculate calc = new Calculate();
You are most of the way there, you just need to use a double array to gather the inputs, and you need to use a loop to save all the inpets to the array:
//use an array instead of a single double
double[] dblArr = new double[5];
int inputs = 0;
//Use a loop to gather 5 inputs
while(inputs < 5){
utils.print("Please enter the next of 5 numbers: ");
dblArr[inputs] = input.nextDouble();
inputs++;
}
//We have changed the add method to static, so you can just use `add(dblArr)` instead of making an instance of the class with the add method
double sum = add(dblArr);
//Finally print out the sum result not the dblArr array
System.out.println("The total is " + sum);
Then just change the method to static so that you can call it directly:
//Add static to this line as shown, because we don't need an instance of this method
public static double add(double[] values) {
int sum = 0;
for (double i : values)
sum += i;
return sum;
}
A bit of a beginner with programming so do bear with me.
I've created an ArrayList inside a HashMap so that all my values can be added up to become a sum so that I can then divide the sum, by the number of entries to the ArrayList, which would give me my average... which is all working fine EXCEPT:
My first entry into my ArrayList is always coming back as 0.0 even when in the GUI I'm entering like 45 or whatever. How can I change it so that my ArrayList stops putting 0 on my first entry? As I've created an averaging program that would work if my first ArrayList entry was retrieving the correct entry, as oppose to the 0 it is bringing back everytime.
Here is my code:
public void addModRes( String mod, Integer res ) {
ArrayList<Integer> nums = myMap.get(mod);
if (nums == null) {
nums = new ArrayList<Integer>();
}
double sum = 0;
double test =0;
double avg =0;
for (Integer number : nums) {
sum += number;
}
//except sum is missing out the first entry in the ArrayList
System.out.println("The Sum of all the numbers in the array is " + sum);
nums.add(res);
myMap.put(mod, nums);
test = nums.size();
//System.out.println("This is the size of the array list "+
numbers.size());
avg = sum/test;
System.out.println("this is the average: "+ average);
}
I tried to understand your code and my guess is that you want something like this:
You want a HashMap<String, ArrayList<Interger>> that stores lists of numbers (the ArrayList<Integer> from the HashMap) that can be identified with their id (the String in the HashMap).
Add a new list to the HashMap
Let's assume that we have an instance variable listMap in our class.
public int createList(String listId) {
this.listMap.put(listId, new ArrayList<Integer>() );
return this.listMap.size();
}
This will add a new ArrayList<Integer> to the listMap.
Add numbers to a certain list
We now write a new method to add numbers to a certain list
public int addNumberToList(String listId, Integer number) {
this.listMap.get(listId).add(number);
return this.listMap.get(listId).size();
}
Calculate the average for a certain list
Now we can use the lists to calculate their average
public double averageForList(String listId){
double sum = 0;
double average = 0;
for (Integer number : this.listMap.get(listId) )
{
sum += number;
}
if (this.listMap.get(listId).size() != 0) average = sum / this.listMap.get(listId).size();
return average;
}
And that should be it.
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;
}
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.
I have an ArrayList of doubles, and i need to find the average between all numbers.
The amount of Double instances in the arraylist is not constant, could be 2, could be 90
I have been trying for hours to get the algorithm myself but could not get it to work in anyway.
do you have any advice? or maybe you can link me to an existing library to get this average?
Thank you
Create a sum variable:
double sum = 0;
Go through the elements in the list using a for-loop:
for (double d : yourList)
in each iteration, add to sum the current value:
sum += d;
after the loop, to find the average, divide sum with the number of elements in the list:
double avg = sum / yourList.size();
Here's for everyone that thinks this was too simple...
The above solution is actually not perfect. If the first couple of elements in the list are extremely large and the last elements are small, the sum += d may not make a difference towards the end due to the precision of doubles.
The solution is to sort the list before doing the average-computation:
Collections.sort(doublesList);
Now the small elements will be added first, which makes sure they are all counted as accurately as possible and contribute to the final sum :-)
If you like streams:
List<Number> list = Arrays.asList(number1, number2, number3, number4);
// calculate the average
double average = list.stream()
.mapToDouble(Number::doubleValue)
.average()
.getAsDouble();
The definition of the average is the sum of all values, divided by the number of values. Loop over the values, add them, and divide the sum by the size of the list.
If by "average between all numbers" you mean the average of all the doubles in your list, you can simply add all the doubles in your list (with a loop) and divide that total by the number of doubles in your list.
Have you tried:
List<Double> list = new ArrayList<Double>();
...
double countTotal = 0;
for (Double number : list)
{
countTotal += number;
}
double average = countTotal / list.size();
Maybe I haven't got the question... but it's not something like this?
double sum = 0.0;
for (double element : list) {
sum += element;
}
double average = sum / list.size();
If you're worried about overflow as you sum the whole list together, you can use a running average. Because it has more operations, it will be slower than adding everything together and dividing once.
for (int x = 0; x < list.size(); x++)
average = (average / (x+1)) * (x) + list.get(x) / (x+1);