Java returning numbers below the avg - java

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

Related

return the sum of int[ [duplicate]

This question already has answers here:
How do you find the sum of all the numbers in an array in Java?
(28 answers)
Closed 1 year ago.
This is my code using loops. Assume that num is not null or empty;
public int[] num;
public double[] sumNum() {
double[] sum;
for (int i = 0; i < num.length; i++) {
sum = sum + num[i];
}
return sum;
}
If you want to devise a function to sum the values of an array, consider the below:
public int sumNum(int[] num) {
int sum = 0;
for (int i = 0; i < num.length; i++) {
sum = sum + num[i];
}
return sum;
}
It doesn't make sense to return a double for a function like this, but you still can. I changed it to int since num is always int as per its declaration. I'm only making an assumption to what you really wanted.
Also consider taking num as argument for the function, thereby giving it local scope within the function. You could keep it global but again, I'm making an assumption of what you really want. Plus, it allows for re-using this function if you ever wanted to find the sum of something else.
You also want some initial value for sum: since you're summing the values in an array, I initialized sum to 0. Otherwise, when you do sum = sum + num[i], what exactly is sum initially? You need some starting point.

What to change in my code to calculate sample Standard deviation instead of population standard deviaiton?

My code calculates the population deviation when I need it to calculate the sample deviation I have compared both formulas and tried changed my calculations but nothing seems to work. Thanks for everyone's help or input in advance.
public class MeanAndStandardDeviation {
public static void main (String argv []) throws IOException {
BufferedReader stdin =
new BufferedReader (new InputStreamReader (System.in));
NumberFormat nf = new DecimalFormat ("0.00");
nf.setMinimumFractionDigits (2);//Sets Min digits
nf.setMaximumFractionDigits (2);//Sets Max digits
String inputValue;
int count = 0;
//For Loop for count
for(int i = 0; i < count; i++){
count++;
}
double varianceFinal = 0;
List<String> input = new ArrayList<String>();//String ArrayList
List<Double> numbers = new ArrayList<Double>();//Double ArrayList
//While loop that takes in all my input and assigns it to the ArrayLists
//Parameters set for when null is entered and total numbers go over 500
while((inputValue = stdin.readLine()) != null && !inputValue.equals("") && input.size()<500){//Parameters set for when null is entered and total numbers go over 500
input.add(inputValue);
numbers.add (Double.parseDouble(inputValue));
}
System.out.println ("Standard Deviation: " +(nf.format(calcStdDev (numbers, count, varianceFinal))));//Prints the Standard Deviation
}
//StandardDeviation Class
static double calcStdDev (List<Double> numbers, int count, double variance){
variance = 0;
double sum = 0;
for(int i = 0; i < numbers.size(); i++){
sum += numbers.get(i);
variance += numbers.get(i) * numbers.get(i);
count++;
}
double varianceFinal = ((variance/count)-(sum*sum)/(count*count));
return Math.sqrt(varianceFinal);
}
}
Seriously, your code is "wrong" on many levels. So instead of debugging all of that for you, I will give you some hints how to fix and simplify your code - then it should be very easy for you to fix/resolve your actual math problem.
First of all, your code is so written in a confusing style that just makes it much harder to understand (and therefore debug) than it needs to be.
Example:
int count = 0;
//For Loop for count
for(int i = 0; i < count; i++){
count++;
}
That for loop doesn't do anything. And even when the condition would be something else, like i < someNumber; you would still just need to put count = someNumber there; instead of looping!
Same here: what is the point of providing count as argument to your calc methods?! And to then just increase it? So, lets rewrite that:
public static double calcStdDev (List<Double> numbers, double variance) {
double sumOfNumbers = 0;
double sumOfSquares = 0;
for(double number : numbers) {
sumOfNumbers += number;
sumOfSquares += number * number;
}
... and instead of calculating count, you simply have
int numberOfNumbers = numbers.size();
... and now, do your math
The other thing that is really strange in your code is how you setup your variance variable; and how it is used within your calc methods.
Long story short: step back and remove everything from your code that isn't required.
It is a bad idea to compute the variance as you do. If the mean is largeish, eg 10 million, and the noise is smallish, eg around 1 then the limited precision of doubles may well mean that your computed variance is negative and the the sd will be nan.
You should either compute it in two passes, eg
double mean = 0.0;
for( i=0; i<n; ++i)
{ mean += x[i];
}
mean /= n;
double var = 0.0;
for( i=0; i<n; ++i)
{
double d = x[i] - mean;
var += d*d;
}
var /= n;
or in one pass, eg
double mean = 0.0;
double var = 0.0;
for( i=0; i<n; ++i)
{
double f = 1.0/(i+1);
double d = x[i]-mean;
mean += d*f;
var = (1.0-f)*(var + f*d*d);
}
(it takes a bit of tedious algebra to show that the one pass method gives the same answer as the two pass method).

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