Jump to content

Java: Summing values of Arrays and Dividing them to get the average in a for-loop

Hip
Go to solution Solved by Hip,
import javax.swing.*;
import java.util.*;

public class Aufgabe42
{
	public static void main(String[] args)
	{
		//Variablen Deklaration
		String eingabe, ausgabe, anfrageZahl;
		double[] arrayZahlen;
		int anzahl;
		
		//Eingabe
		eingabe = JOptionPane.showInputDialog(null, "Geben Sie die Anzahl der Zahlen an.");
		
		//Variablen Initialisierung
		anzahl = Integer.parseInt(eingabe);
		arrayZahlen = new double[anzahl];
		
		//Anfrage der jeweiligen Zahlen
		for(int i = 0; i < anzahl; i++)
		{
			anfrageZahl = JOptionPane.showInputDialog(null, "Geben Sie eine Zahl an:");
			arrayZahlen[i] = Double.parseDouble(anfrageZahl);
		}
		
		//Ausgabe
		JOptionPane.showMessageDialog(null, "Der Durchschnitt beträgt: " + erhaltenDurchschnitt(arrayZahlen));
		System.exit(0);
	}
	
	public static double erhaltenDurchschnitt(double[] arrayZahlen)
	{
		//Variablen Deklaration
		double arraySumme, durchschnitt;
		
		//Initialisierung
		arraySumme = 0;
		
		//Addieren aller Array Werte
		for(int i = 0; i < arrayZahlen.length; i++)
		{
			arraySumme += arrayZahlen[i];
		}
		
		//Berechnung des Durchschnitts
		durchschnitt = arraySumme / arrayZahlen.length;
		
		return durchschnitt;
	}
}

 

The solution above is without converting the double to String at all and it works out.

Hey guys,

 

I have a code where I give the array length first, then I put numbers in the array.

 

And now I need your help, I want to sum up the values of the array and then divide them by the number of array length to get the average value of the array.

 

Thank you in advance!

15517983279208769137550717182479.jpg

Link to comment
Share on other sites

Link to post
Share on other sites

simply increment a variable and divide by the length of the array.

 

here a sample

 

double sum = 0;
for (double value : yourArray) 
{
    sum += value;
}

double average = (double)sum / yourArray.length

 

Link to comment
Share on other sites

Link to post
Share on other sites

You calculate average and return it at the "durchschnitt" method (which I renamed here to "erhaltenDurchschnitt") like this:

public static double erhaltenDurchschnitt(double[] d)
{
  double sum = 0;
  
  for(int i = 0; i < d.length; i++)
  {
    sum += d[i];
  }
  
  return sum / d.length;
}

Then at the end of the "main" method you add:

JOptionPane.showMessageDialog(frame, "Der Durchschnitt betragt " + erhaltenDurchschnitt(durchschnitt));
System.exit(0);

 

Link to comment
Share on other sites

Link to post
Share on other sites

public static double durchschnittBerechnen(double[] durchschnitt)
{

	//Variablen Deklaration
    double arraySumme = 0;
    
    //alle Werte aus dem Array addieren
    for (int i = 0; i < durchschnitt.length; i++)
    {
    	arraySumme += durchschnitt[i];
    }
    
    //Durchschnitt = Gesamtsumme / Anzahl
    double durchschnitt = arraySummme / durchschnitt.length;
    
    //Ausgabe
    //Ich würde diesen Teil in einer eigenen Funktion lösen, um Funktionalität und Darstellung zu trennen. Also lieber einfach:
    
    //Rückgabe
    return durchschnitt;
}

public static void main(String args[]) {

	//Aktuell heißt viel in deinem Code einfach nur 'durchschnitt', was dich garantiert später verwirrend wird. Verwende sprechende Namen!
    //Variablen Deklaration
    String eingabe, anfrageZahl;
    int anzahl;
    
    //Eingabe
    eingabe = JOptionsPane.showInputDialog(null, "Geben Sie die Anzahl der Zahlen an.");
    
    //Initialisierung
    anzahl = Int.parseInt(eingabe);
    double[] zahlenArray = new double[anzahl];
    
    //Anfrage der Zahlen
    for (int i = 0; i < anzahl; i++)
    {
    	anfrageZahl = JOptionsPane.showInputDialog(null, "Geben Sie eine Zahl an:");
        zahlenArray[i] = Double.parseDouble(anfrageZahl);
    }
    
	double arrayDurchschnitt = durchschnittBerechnen(zahlenArray);

}

I haven't touched Java in a while, so there may be some mistakes.

But basically all you have to do is iterate over the elements of the array and add them together, the average is the sum of the Array divided by the length of the Array.

 

Also, be sure to use more descriptive names, a lot of stuff in your code is just called 'durchschnitt'

75% of what I say is sarcastic

 

So is the rest probably

Link to comment
Share on other sites

Link to post
Share on other sites

Simple way to achieve it:

// Two ints which will serve for the calculations. Ints because I assume no decimal numbers
int Average = 0;
int SumOfAll = 0;
for (int i = 0; i < ArrayName.Length; i++
     {
       // Basically this for loop goes through all values in the array and adds them onto 'SumOfAll'
       // Of course these all have to be numbers
     	SumOfAll += ArrayName[i];
     }
// Now to calculating the average; dividing the sum of all numbers by the amount of values in the array
Average = SumOfAll / Array.Length;

 

 

(I see others have posted the answer already, but whatever..)

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, Franck said:

simply increment a variable and divide by the length of the array.

 

here a sample

 


double sum = 0;
for (double value : yourArray) 
{
    sum += value;
}

double average = (double)sum / yourArray.length

 

 

2 minutes ago, svegori1950 said:

You calculate average and return it at the "durchschnitt" method (which I renamed here to "erhaltenDurchschnitt") like this:


public static double erhaltenDurchschnitt(double[] d)
{
  double sum = 0;
  
  for(int i = 0; i < d.length; i++)
  {
    sum += d[i];
  }
  
  return sum / d.length;
}

Then at the end of the "main" method you add:


JOptionPane.showMessageDialog(frame, "Der Durchschnitt betragt " + erhaltenDurchschnitt(durchschnitt));
System.exit(0);

 

Beat me to it :P

75% of what I say is sarcastic

 

So is the rest probably

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, myselfolli said:

 

Beat me to it :P

Yeah but i didn't re-wrote his whole code in a code block ?

Link to comment
Share on other sites

Link to post
Share on other sites

3 minutes ago, Franck said:

Yeah but i didn't re-wrote his whole code in a code block ?

There were just a few points I was itching to make. Plus I haven't really been doing a lot with Java lately, so I kinda had to get back into the syntax (especially comming from JS that took longer than I'd like to admit) :P

75% of what I say is sarcastic

 

So is the rest probably

Link to comment
Share on other sites

Link to post
Share on other sites

On 3/5/2019 at 4:25 PM, svegori1950 said:

You calculate average and return it at the "durchschnitt" method (which I renamed here to "erhaltenDurchschnitt") like this:


public static double erhaltenDurchschnitt(double[] d)
{
  double sum = 0;
  
  for(int i = 0; i < d.length; i++)
  {
    sum += d[i];
  }
  
  return sum / d.length;
}

Then at the end of the "main" method you add:


JOptionPane.showMessageDialog(frame, "Der Durchschnitt betragt " + erhaltenDurchschnitt(durchschnitt));
System.exit(0);

 

It somehow doesn't work.

 

Aufgabe42.java:27: error: incompatible types: void cannot be converted to String
                ausgabe = JOptionPane.showMessageDialog(null, "Der Durchschnitt betr├ñgt: " + erhaltenDurchschnitt(durchschnitt));

 

@myselfolli Wie meinst du dass mit der eigenen Funktion für die Ausgabe? 

 

 

 

 @Minibois @svegori1950 

import javax.swing.*;

public class Aufgabe42
{
    public static void main(String[] args)
    {
        //Variablen Deklaration
        String eingabe, ausgabe, anfrageZahl;
        double[] arrayZahlen;
        int anzahl;
        
        //Eingabe
        eingabe = JOptionPane.showInputDialog(null, "Geben Sie die Anzahl der Zahlen an.");
        
        //Variablen Initialisierung
        anzahl = Integer.parseInt(eingabe);
        arrayZahlen = new double[anzahl];
        
        //Anfrage der jeweiligen Zahlen
        for(int i = 0; i < anzahl; i++)
        {
            anfrageZahl = JOptionPane.showInputDialog(null, "Geben Sie eine Zahl an:");
            arrayZahlen = Double.parseDouble(anfrageZahl);
        }
        
        //Initialisierung und Ausgabe
        ausgabe = JOptionPane.showMessageDialog(null, "Der Durchschnitt beträgt: " + erhaltenDurchschnitt(arrayZahlen));
        System.exit(0);
    }
    
    public static double erhaltenDurchschnitt(double[] arrayZahlen)
    {
        //Variablen Deklaration

        double arraySumme;
        
        //Initialisierung
        arraySumme = 0;
        
        //Addieren aller Array Werte
        for(int i = 0; i < arrayZahlen.length; i++)
        {
            arraySumme += arrayZahlen;
        }
        
        //Berechnung des Durchschnitts
        return arraySumme / arrayZahlen.length;
    }
}

 

Link to comment
Share on other sites

Link to post
Share on other sites

53 minutes ago, Hip said:

It somehow doesn't work.

 

Aufgabe42.java:27: error: incompatible types: void cannot be converted to String
                ausgabe = JOptionPane.showMessageDialog(null, "Der Durchschnitt betr├ñgt: " + erhaltenDurchschnitt(durchschnitt));

 

 

erhaltenDurchschnitt(durchschnitt) return a double. You need to convert to string the value on the show dialog line (not the method)

Link to comment
Share on other sites

Link to post
Share on other sites

import javax.swing.*;
import java.util.*;

public class Aufgabe42
{
	public static void main(String[] args)
	{
		//Variablen Deklaration
		String eingabe, ausgabe, anfrageZahl;
		double[] arrayZahlen;
		int anzahl;
		
		//Eingabe
		eingabe = JOptionPane.showInputDialog(null, "Geben Sie die Anzahl der Zahlen an.");
		
		//Variablen Initialisierung
		anzahl = Integer.parseInt(eingabe);
		arrayZahlen = new double[anzahl];
		
		//Anfrage der jeweiligen Zahlen
		for(int i = 0; i < anzahl; i++)
		{
			anfrageZahl = JOptionPane.showInputDialog(null, "Geben Sie eine Zahl an:");
			arrayZahlen[i] = Double.parseDouble(anfrageZahl);
		}
		
		//Ausgabe
		JOptionPane.showMessageDialog(null, "Der Durchschnitt beträgt: " + erhaltenDurchschnitt(arrayZahlen));
		System.exit(0);
	}
	
	public static double erhaltenDurchschnitt(double[] arrayZahlen)
	{
		//Variablen Deklaration
		double arraySumme, durchschnitt;
		
		//Initialisierung
		arraySumme = 0;
		
		//Addieren aller Array Werte
		for(int i = 0; i < arrayZahlen.length; i++)
		{
			arraySumme += arrayZahlen[i];
		}
		
		//Berechnung des Durchschnitts
		durchschnitt = arraySumme / arrayZahlen.length;
		
		return durchschnitt;
	}
}

 

The solution above is without converting the double to String at all and it works out.

Link to comment
Share on other sites

Link to post
Share on other sites

Spoiler
On 3/6/2019 at 9:31 PM, Hip said:

It somehow doesn't work.

 

Aufgabe42.java:27: error: incompatible types: void cannot be converted to String
                ausgabe = JOptionPane.showMessageDialog(null, "Der Durchschnitt betr├ñgt: " + erhaltenDurchschnitt(durchschnitt));

 

@myselfolli Wie meinst du dass mit der eigenen Funktion für die Ausgabe? 

 

 

 

 @Minibois @svegori1950 



import javax.swing.*;

public class Aufgabe42
{
    public static void main(String[] args)
    {
        //Variablen Deklaration
        String eingabe, ausgabe, anfrageZahl;
        double[] arrayZahlen;
        int anzahl;
        
        //Eingabe
        eingabe = JOptionPane.showInputDialog(null, "Geben Sie die Anzahl der Zahlen an.");
        
        //Variablen Initialisierung
        anzahl = Integer.parseInt(eingabe);
        arrayZahlen = new double[anzahl];
        
        //Anfrage der jeweiligen Zahlen
        for(int i = 0; i < anzahl; i++)
        {
            anfrageZahl = JOptionPane.showInputDialog(null, "Geben Sie eine Zahl an:");
            arrayZahlen = Double.parseDouble(anfrageZahl);
        }
        
        //Initialisierung und Ausgabe
        ausgabe = JOptionPane.showMessageDialog(null, "Der Durchschnitt beträgt: " + erhaltenDurchschnitt(arrayZahlen));
        System.exit(0);
    }
    
    public static double erhaltenDurchschnitt(double[] arrayZahlen)
    {
        //Variablen Deklaration

        double arraySumme;
        
        //Initialisierung
        arraySumme = 0;
        
        //Addieren aller Array Werte
        for(int i = 0; i < arrayZahlen.length; i++)
        {
            arraySumme += arrayZahlen;
        }
        
        //Berechnung des Durchschnitts
        return arraySumme / arrayZahlen.length;
    }
}

 

 

Hey, I've always been taught to use the EVA-approach to programming, so splitting the input (Eingabe), processing (Verarbeitung) and output (Ausgabe) into different functions to increase reusability of your code

75% of what I say is sarcastic

 

So is the rest probably

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×