Java calculating average of numbers from another file - java

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;
}

Related

Java returning numbers below the avg

ne of my projects assigned was to create an array for 10 variables which the user inputs and to have the program output the average of the input number as well as listing the numbers below the average. I am able to obtain the average without an issue but my code to return the numbers below the average seems to not be doing the job. For example if I input into the array the values [1,2,3,4,5,6,7,8,9,10] the average outputs as 5.5 (which is good) but the output I want from BelowAverage is 1,2,3,4,5 can anyone help me?
public static double BelowAverage(ArrayList<Double> Averages) {
int i, aveless = 0; double avg = 0;
for(i = 0; i < Averages.size(); i++)
avg = Averages.get(i);
avg /= Averages.size();
for(i = 0; i < Averages.size(); i++)
if(Averages.size() < avg)
aveless++;
return aveless;
}
No need to use wrappers, you could use double instead of Double.
Your variable naming is weird, why do you have an ArrayList of averages instead of numbers?
Follow Java naming conventions:
firstWordLowerCaseVariable
firstWordLowerCaseMethod()
FirstWordUpperCaseClass
ALL_WORDS_UPPER_CASE_CONSTANT
and use them consistently
You already have a method that calculates the average, why not use it?
So, for example, your code might look like this (with slight modifications):
public static int belowAverage(List<Double> numbers) {
double avg = calculateAverages(numbers); //Go, get the average using the method you already have
int aveless = 0;
for (int i = 0; i < numbers.size(); i++) {
if (numbers.get(i) < avg) { //Instead of comparing the numbers array size, compare the number against the average.
aveless++;
}
}
return aveless;
}
I added opening and closing curly braces for the for loop as I think it's easier to read that way.
I also changed the return type to int instead of double on this method as you only want to count, so, decimal point is not needed and moved the System.out.println() call inside the calculateAverage() method to the main method.
I also changed the parameter type to the interface one (from ArrayList to List)
Your problem seems to bee on this line:
if(Averages.size() < avg) aveless++;
You should be checking Averages.get(i) < avg instead, otherwise what is the point of looping?
If I understand correctly, and you want a list with all the numbers below the average, you should change the return value and the code, like this:
public static ArrayList<Double> BelowAverage(ArrayList<Double> Averages) {
// You already have a method for calculating the average, so use it
double avg = CalculateAverages(Averages);
ArrayList<Double> aveless = new ArrayList<Double>();
int i;
for(i = 0; i < Averages.size(); i++){
double number = Averages.get(i);
if(number < avg){
aveless.add(number);
}
}
return aveless;
}
There are several problems with your code. Let's go through them one at a time.
First problem:
for(i = 0; i < Averages.size(); i++)
avg = Averages.get(i); //this line
avg /= Averages.size();
You are simply reassigning the value of avg in the loop. What you want to do is to keep adding values to it. Replace = with += to get avg += Averages.get(i);.
Second problem:
for(i = 0; i < Averages.size(); i++)
if(Averages.size() < avg)
aveless++;
Here you are checking whether avg is larger than the size of the list which is not what you want to be doing. What you wonder is whether avg is larger than the values in the list. You need to replace Averages.size() with Averages.get(i). This is a relatively easy mistake to spot because the loop is not really achieving anything right now, so look out for things like this.
Edit: There are a few other problems as well. avg should be a double and not an int, because ints cannot store decimal places and there is no guarantee that your average is a whole number, so you will get a rounding error. Furthermore, your method should return an int instead of a double because "the number of values below average" is always an integer.
To count the number of 'numbers' which have less value than the average, you should compare each element inside that array with the average, not with the size of the array. Try it as follows:
public static double BelowAverage(ArrayList<Double> Averages) {
int i, aveless = 0; double avg = 0;
for(i = 0; i < Averages.size(); i++)
avg = Averages.get(i);
avg /= Averages.size();
for(Double a : Averages)
if(a < avg) aveless++;
return aveless;
}

Java: Calculating average GPA with intArr of 12 students

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;
}

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 recollecting the randomly chosen enums and summing it all up

A mere continuation of this article
Java How to get the sum up all the of the values of each enum
full source code below
http://pastebin.com/VMGUJmeZ
I have this For loop below, and what I am here to ask you guys for today is how I could recollect all of the randomly chosen enums, and sum up all their values.
for (int i = amount; i > 0; --i){//determines the amount of cycles.
Junk randomX = Junk.values()[random.nextInt(Junk.values().length)];
//randomly picks an enum
System.out.println(randomX);
}
Below me is the solution I did which basically declared a int sum, initialize it and put it in the for loop to collect the values of the enums
for (int i = amount; i > 0; --i){
Junk randomX = Junk.values()[random.nextInt(Junk.values().length)];
//randomly picks an enum
System.out.println(randomX);
for(Junk o : Junk.values()){
sum += o.getValue();
//sorry, I had sum declared and initialized outside of the loop.
System.out.println(sum);
}
}
sadly, the output was not desirable
Dresser
0
150
400
650
650
650
...
I understand that I am basically asking others to help me in writing code for me, but I am unsure of how else to do this.
Also I understand it might be impossible to do considering that the only way to get the sum of the enum's value is by doing it outside of the for loop, which will then make the solution impossible as it will only get all of the values.
Perhaps there is something besides a for loop I could use, that someone could recommend me in using.
You have a second loop
for(Junk o : Junk.values()){
sum += o.getValue();
//sorry, I had sum declared and initialized outside of the loop.
System.out.println(sum);
}
which is not neccessary. Simply replace this part by
sum += randomX.getValue();
System.out.println(sum);
int sum = 0;
for (int i = amount; i > 0; --i){
Junk randomX = Junk.values()[random.nextInt(Junk.values().length)];
//randomly picks an enum
System.out.println(randomX);
sum += randomX.getValue();
System.out.println(sum);
}
System.out.println("grand total: " + sum);

Categories

Resources