How to calculate average of array input? - java

I've just recently started programming Java and I'm having a problem that's making me want to break things. It starting to get annoying, and I'm feeling pretty stupid right now.
The task is to write a program that asks for five numbers to be input into an array (yes, can't use a list) and to then calculate the average of the five numbers input.
Where am I going wrong?
My current code calculates the average after each input. I want to do that after they've all been inserted, otherwise what is the point?
All help is greatly appreciated, you believe me!
Here's the code:
import java.util.Scanner;
public class Uppg3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[5];
int sum = 0;
for (int i = 0; i < numbers.length; i++)
{
System.out.println("enter a number: ");
numbers[i] = input.nextInt();
sum = numbers[i];
}
double average = sum / 5;
System.out.println("Average is " + average);
input.close();
}
}

You ought to encapsulate such a thing in a method.
You can either process all the numbers at once by storing them in an array and passing them at the same time or keep a running tally and return it on request.
public class StatisticsUtils {
private double sum;
private int numValues;
public StatisticsUtils() {
this.sum = 0.0;
this.numValues = 0;
}
public void addValue(double value) {
this.sum += value;
++this.numValues;
}
public double getAverage() {
double average = 0.0;
if (this.numValues > 0) {
average = this.sum/this.numValues;
}
return average;
}
public static double getAverage(double [] values) {
double average = 0.0;
if ((values != null) && (values.length > 0)) {
for (double value : values) {
average += value;
}
average /= values.length;
}
return average;
}
}

Looking at this for loop
for (int i = 0; i < numbers.length; i++)
{
System.out.println("enter a number: ");
numbers[i] = input.nextInt();
sum = numbers[i];
}
You are adding it to the array just fine, but you keep setting the sum to whatever they enter. For example, if I enter 5 3 2, the array will have 5 3 2 in it, but the sum will be set to 2. If I only entered 5 3, it would be set to 3.
One solution would be to use +=, that way it adds that number to whatever the current value is (which you start at 0). It's also important to note that when you divide two integers (sum and 5), it will not give you a decimal. This can be solved by using 5.0 or casting sum to a double.

Your code is currently just assigning a different value to sum on every iteration of the loop. You need to change sum = numbers[i]; to sum += numbers[i]; (equivalent to sum = sum + numbers[i];). You'll also want to change int sum = 0; to double sum = 0 so that your answer has decimals.

Ok, it works with the "+=", love you Chris Phelps. That and changing:
int sum = 0;
to
double sum = 0;
To make the answer have a decimal. Thanks a lot you guys! A weight has been lifted of my chest :).

Code for calculating average of array input
package com.imedxs;
import java.util.Scanner;
public class Test {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("for calculating average of array");
int n=0;
int b=sc.nextInt();
int[] numbers = new int[b];
int sum = 0;
for (int i = 0; i < b; i++)
{
System.out.println("enter a number: ");
numbers[i] = sc.nextInt();
sum += numbers[i];
n++;
}
double average = sum / n;
System.out.println("Average is " + average);
}
}

Related

Simple Java- The sentinal value keeps being calculated in my count and average?

For a homework assignment i need to take an unspecified number of grades( no more than 100), get the average, and display how many are above and below average. I'm trying to use a Sentinal value to exit the loop when putting in grades. And while it does exit the loop, it also takes the Sentinal value as a grade input and calculates that into the average. For example if I enter scores "50 75 100" then exit with -1. the results will display something like 74.66666666667. I can sort of see why it is doing this looking at my for loop but I'm struggling to find a way to fix it.
public class AnalyzeScores {
public static void main(String[] args) {
double scores, average;
int aboveAvg, belowAvg;
double sum = 0;
int count = 0;
Scanner input = new Scanner(System.in);
double[] scoresList = new double[100];
for (int i = 0; i < 100; i++) {
System.out.print("Enter Score " + (i + 1) + "(negative score exits): ");
scoresList[i] = input.nextDouble();
sum = sum + scoresList[i];
count++;
if (scoresList[i] < 0) {
average = (sum / i);
System.out.println("average is " + average);
return;
}
}
}
}
you should move this piece of code:
sum = sum + scoresList[i];
count++;
from before the if condition to after the if condition.
That's because you put -1 to your list while calculating the average. You need to check if the input value is below zero before adding it to scoresList.
Here is the code where this problem is fixed (but it still requires some improvements):
public class Main {
public static void main(String[] args) {
double scores, average;
int aboveAvg, belowAvg;
double sum = 0;
int count = 0;
Scanner input = new Scanner(System.in);
double[] scoresList = new double[100];
for (int i = 0; i < 100; i++) {
System.out.print("Enter Score " + (i + 1) + "(negative score exits): ");
double score = input.nextDouble();
if (score >= 0) {
scoresList[i] = score;
sum = sum + scoresList[i];
count++;
}
else break;
}
average = (sum / count);
System.out.println("average is " + average);
}
}

array printing as memory location and sentinel value not working

I am having some issues with some homework that I cannot figure out, if someone could point me in the correct direction I would greatly appreciate it. My sentinel value is not working at all and I cannot figure it out so that it works. Also my array for my averages is printing out as memory locations and not the value. Here is the code I have so far
public class DistanceFromAverage
{//Global Declaration Section
public static void main(String args[])
{//Declaration Section
double[] Numbers;
double[] Average;
//Input Section
Numbers = array_numbers();
//Processing Section
Average = distance_average(Numbers);
//Output Section
display_array(Numbers, Average);
}//end
public static double[] array_numbers()
{
double[] tmp;
tmp = new double[20];
double[] sentinel = {99999};
Scanner input = new Scanner(System.in);
int count = 0;
try
{
for (int i = 0; i < tmp.length; i++)
{
System.out.println("Please enter number");
tmp[i] = input.nextDouble();
}
}
catch(InputMismatchException exception)
{
System.out.println("A number must be entered");
System.exit(0);
}
return tmp;
}//end array
public static double[] distance_average(double[] Numbers) {
double sum = 0.0;
for (int i=0; i < Numbers.length; i++)
sum = sum + Numbers[i];
double average = sum / Numbers.length;
return new double[] {average};
} // determine average
public static void display_array(double[] Numbers, double[] Average)
{
for (int i = 0; i < Numbers.length; i++){
System.out.println("The numbers in the array are: " + Numbers[i] + "and the average is" + Average);
}
}//end display_array
}//end class
Regarding Average being printed as Memory Location,
Your display function accepts Average as an Array and not as a simple double.
This will call toString() on your Array class.
Since Average is just a single number, either use Average[0] in your 'System.out.println' statement or accept a simple average of type double in your display method like below:
public static void display_array(double[] Numbers, double Average)
and change the signature of
public static double[] distance_average(double[] Numbers) {
to
public static double distance_average(double[] Numbers) {

Java - How to break out of for loop by comparing items in an array

I need to break out of the for loop if the user enters 99999.The code below wont break the loop and actually calculates 99999 into the average. Thank you in advance for any help.
import java.util.*;
public class DistanceFromAverage {
public static void main(String[] args)
{
//User input
Scanner input = new Scanner(System.in);
double[] someNum = new double[10];
double sum = 0;
double avg;
for(int x =0; x < someNum.length; x++)
{
if(someNum[x] != 99999)
{
System.out.print("Enter a number >>");
someNum[x] = input.nextDouble();
sum = sum + someNum[x];
}
else
{break;}
}
//Figuring the average
avg = sum/10;
//Output
for(int y = 0; y < someNum.length; y++)
{
double distance = (someNum[y]-avg);
System.out.print(someNum[y]);
System.out.println(" Distance from average >> " + distance);
}
System.out.println("Average>> " + avg);
}
}
Your logic is messed up. You're asking for up to 10 numbers from the user. You've defaulted the array of input numbers to 0. When the user enters 99999, it gets added to the array, then on the next time through the loop, it looks for the next number to compare to 99999 and gets 0.
The entire logic should be rearranged to ask for up to 10 numbers, check the number immediately. If the user enters 99999, then break. Otherwise, put them into an array, keep a count, and average them.
I haven't tested this, but I've rearranged the logic a little which should set you on the right path.
List<Double> someNum = new ArrayList<Double>();
do {
System.out.print("Enter a number >>");
double thisNum = input.nextDouble();
if (thisNum == 99999) {
break;
}else {
someNum.add(thisNum);
sum += thisNum;
}
}while (true);
//Figuring the average
avg = someNum.size() == 0 ? 0 : sum / someNum.size();
for(double thisNum : someNum) {
double distance = (thisNum - avg);
System.out.print(thisNum);
System.out.println(" Distance from average >> " + distance);
}
//Output
System.out.println("Average>> " + avg);
How about using this as the for block:
System.out.print("Enter a number >>");
double inputValue = input.nextDouble();
if(inputValue == 99999){
break;
}
someNum[x] = inputValue;
sum = sum + someNum[x];
You won't be able to use x outside the loop as is, so use maybe another variable or maybe alter the for statement to not declare x to be local to the loop.
Using a well-thought-out while loop would be better.
You can use an ArrayList and simply specify the loop to increment 10 times for the getInput() method, and then specify the loop to only calculate average based on the .size() of the ArrayList.
This should fix it up for you, and break properly and calculate the average based on numbers input up until the 99999.
import java.util.*;
class DistanceFromAverage {
ArrayList<Double> numbers = new ArrayList<Double>();
double sum = 0;
double avg;
DistanceFromAverage() {
getInput();
calculateAverage();
showOutput();
}
void getInput() {
Scanner input = new Scanner(System.in);
for (int x = 0; x < 10; x++) {
System.out.println("Enter a number >>");
double num = input.nextDouble();
if (num == 99999) break;
else {
numbers.add(num);
sum += num;
}
}
}
void calculateAverage() {
avg = sum / 10;
}
void showOutput() {
for (int x = 0; x < numbers.size(); x++) {
double distance = (numbers.get(x) - avg);
System.out.println(numbers.get(x) + " Distance from average >> " + distance);
}
System.out.println("Average >> " + avg);
}
public static void main(String[] args) {
new DistanceFromAverage();
}
}

averaging an array in a separate method

My original code is:
import javax.swing.JOptionPane;
public class average {
public static void main(String[] args) {
String str1;
String str2;
String str3;
int numbersToAverage;
str1 = JOptionPane.showInputDialog("Please enter the amount of numbers you would like to average: ");
numbersToAverage = Integer.parseInt(str1);
// while statement will provide error message so user cannot enter 0
while (numbersToAverage < 1) {
str3 = JOptionPane.showInputDialog("Invalid entry: Please enter one or more numbers to average: ");
numbersToAverage = Integer.parseInt(str3);
}
// array size is set to equal user input
double[] numbers = new double[numbersToAverage];
double sum = 0;
for (int i = 0; i < numbersToAverage; i++) {
str2 = JOptionPane.showInputDialog("Enter number " + (i + 1)
numbers[i] = Double.parseDouble(str2);
// the sum equals numbers in the array added together
sum += numbers[i];
}
// Calculates the average of the numbers entered by the user
double average = sum / numbersToAverage;
// Prints in a dialogue box to user the average
JOptionPane.showMessageDialog(null, "The average of the numbers you entered is: " + average);
}
}
and I am now having to calculate the average in a separate method and I am having a hard time figuring out how to do that? So far I have:
import javax.swing.JOptionPane;
public class average {
public static void main(String[] args) {
String str1;
String str2;
String str3;
int numbersToAverage;
str1 = JOptionPane
.showInputDialog("Please enter the amount of numbers you would like to average: ");
numbersToAverage = Integer.parseInt(str1);
// while statement will provide error message so user cannot enter 0
while (numbersToAverage < 1) {
str3 = JOptionPane
.showInputDialog("Invalid entry: Please enter one or more numbers to average: ");
numbersToAverage = Integer.parseInt(str3);
}
// array size is set to equal user input
double[] numbers = new double[numbersToAverage];
//double sum = 0;
for (int i = 0; i < numbersToAverage; i++) {
str2 = JOptionPane.showInputDialog("Enter number " + (i + 1)
numbers[i] = Double.parseDouble(str2);
JOptionPane.showMessageDialog(null, "The average of the numbers you entered is: " );
}
}
public static double average(double[] array){
double sum;
sum += array[i];
double average = sum / array.length;
return average;
}
}
I am having a hard time figuring out how to call this in the main method and how to get the correct calculation. What is the best way to do this? Do I need a for loop in the average method or should I keep it in the main?
Just do this:
StatUtils.mean(array);
you can find more about StatUtils here.
In Java 8 one might use Streams:
final double avg = array.length > 0 ? DoubleStream.of(array).sum() / array.length : 0;
Or in an own function:
public static double average(final double[] array) {
return array.length > 0 ? DoubleStream.of(array).sum() / array.length : 0;
}
Yes you need a loop, try to do something like this:
public static double average(double[] array) {
if(array.length == 0) {
return 0;
}
double sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
double average = sum / array.length;
return average;
}

How to get the Standard deviation of this array

Ok so i have a code set out to get the mean of an array that has upto 50 elements, i want to also find the standard deviation of those elements and show it right under where it would display the mean, my code so far is
import java.util.Scanner;
public class caArray
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("How many numbers you want to calculate average upto 50 : ");
int n = input.nextInt();
int[] array = new int[50];
int sum = 0;
for (int m = 0; m < n; m++)
{
System.out.print("Number " + m + " : ");
array[m] = input.nextInt();
}
for (int m = 0; m < n; m++)
{
sum = array[m] + sum;
}
{
System.out.println("Total value of Numbers = " + sum);
}
{
double avg;
avg = sum / array.length;
System.out.println("Average of Numbers = " + avg); //calculate average value
}
}
}
i need to add into this to get the standard deviation in the one program
EDIT** I cannot use the functions as i actully have to use the standard deviation fourmula withing the program itself
you can write it in 3 Methods
private double standardDeviation(double[] input) {
return Math.sqrt(variance(input));
}
private double variance(double[] input) {
double expectedVal = expectedValue(input);
double variance = 0;
for(int i = 0;i<input.length;++i) {
double buffer = input[i] - expectedVal;
variance += buffer * buffer;
}
return variance;
}
private double expectedValue(double[] input) {
double sum = 0;
for(int i = 0;i<input.length;++i) {
sum += input[i];
}
return sum/input.length;
}
hope it works, i am not quite shure about it, if i used the formulas the right way.
But basicly you have this 3 mathematical formulas in your calculation
If you don't have to write it yourself, check out Apache Commons Math. The stats documentation references how to derive standard deviations.
As you have to write it yourself, perhaps checking out the source code for DescriptiveStatistics would be instructive (look for the function getStandardDeviation())

Categories

Resources