Java: Summing values of Arrays and Dividing them to get the average in a for-loop
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.
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 accountSign in
Already have an account? Sign in here.
Sign In Now