array printing as memory location and sentinel value not working - java

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) {

Related

Java average method stuck

So guys this is my code. the code runs fine but I don't get the proper average. Could someone please fix it.
import java.util.Scanner;
public class test {
public static double Avg(int amt, int num) {
int tot = 0;
tot = tot + num;
int average = tot/amt;
return average;
public static void main(String[] args) {
double average_ICT_01 = 0;
Scanner sc = new Scanner(System.in);
ArrayList<Integer> ICT_01 = new ArrayList<Integer>();
for (int i=0; i<3; i++) {
int num = sc.nextInt();
ICT_01.add(num);
}
int length01 = ICT_01.size();
for (int c=0; c<3; c++) {
int num1 = ICT_01.get(c);
average_ICT_01 = Avg(length01,num1);
}
System.out.println(average_ICT_01);
}
}
The arithmetic average of n numbers is their sum divided by n. So a method for calculating the average of all the numbers in a vector should be:
public static double avg(List<int> vec){
//Sum all numbers
long sum = 0;
for(int i=0;i<vec.size();i++){
sum = sum + vec.get(i);
}
//Divide by the number of numbers
double avg = sum/vec.size();
//Return the average
return avg;
}

How to calculate average of array input?

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

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

two array multipication in a method

I need to compute the multiplication of the grade[0] to percentage1[0] and then print the result. Can someone help me?
LaboratoryExam.java
import java.util.*;
public class LaboratoryExam {
static Scanner glad=new Scanner(System.in);
static double grades[]=new double[5];
static double percentage1[]=new double[5];
static double comp[]=new double[5];
static double sum=0;
public static void main(String[] args) {
System.out.print("Enter 5 grades: ");
for(int i=0; i<grades.length; i++){
grades[i]=glad.nextDouble();
}
Percentage();
compute(grades,percentage1);
System.out.println("\nSum is: " + sum);
}
public static double[] Percentage(){
double Percentage;
System.out.print("\nEnter 5 Percentage: ");
for(int p=0; p<percentage1.length; p++)
percentage1[p]=glad.nextDouble();
return percentage1;
}
public static double compute( double[] grades, double[] percentage1 ){
for(int i=0; i<comp.length;i++){
double comp=grades[0]*percentage1[1];
System.out.println("Equivalent: "+sum);
double sum=comp+comp;
}
return sum;
}
}
You should do the multiplication with grades[i] and percentage1[i]. Here you're just multiplying the same number over and over. Try this:
double comp=grades[i]*percentage1[i];
Also, I think you're not printing the right thing, since you seem to want to print the result of the multiplication. Try with this:
System.out.println("Equivalent: "+ comp);
Finaly, I think it would be better to declare comp and sum out of the for:
public static double compute( double[] grades, double[] percentage1 ){
double comp;
double sum;
for(int i=0; i<comp.length;i++){
comp=grades[0]*percentage1[1];
System.out.println("Equivalent: "+sum);
sum=comp+comp;
}
return sum;
}
In your compute method, you're getting the product of grades[0] and percentage1[1] for all the iterations. Instead, you should use the elements on the i index as stated in your for loop:
for(int i=0; i<comp.length;i++) {
double comp = grades[i]*percentage1[i];
Also, you're calculating the wrong sum:
for(int i=0; i<comp.length;i++) {
double sum=comp+comp;
}
Here you're shadowing the static double sum declared before, so you will always get 0 when doing return sum;. You should instead use the sum variable declared in your class:
for(int i=0; i<comp.length;i++) {
//note: no re-declaration of sum variable
//also fixed the sum calculation
sum += comp;
}
In the end, your code will look like:
for(int i=0; i<comp.length;i++) {
double comp=grades[i]*percentage1[i];
comp[i] = comp;
sum += comp;
System.out.println("Equivalent: "+sum);
}
return sum;
This is almost good. Make sure you declare the sum variable outside of the for loop so you can retain its value on each iteration of the loop. Also use your array indices to access the correct values. Change it to this:
public static double compute( double[] grades, double[] percentage1 ){
double sum = 0;
for(int i=0; i<comp.length;i++){
comp[i]=grades[i]*percentage1[i];
System.out.println("Equivalent: "+comp[i]);
sum += comp[i];
}
return sum;
}
Also, in your main method, make it:
sum = compute(grades,percentage1);

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