philosophical introvert philosophical introvert - 5 months ago 11
Java Question

How to extract numbers from an array list, add them up and divide by the amount of numbers in the array list?

I was watching a lesson online about arrays. It taught me the 'basics' of array lists: how to create an array list. So I was wondering, how would one go about creating an array list from the users' input (

), extract the numbers out of it, add them up and divide by the total amount of numbers in the array list (long story short, calculate the average of the array)?

Here's my, somewhat of an approach:

import java.util.Arrays;
import javax.swing.JOptionPane;
public class JOptionPaneTesting {

public static void main(String[] args){
int grades = Integer.parseInt(JOptionPane.showInputDialog("What are your grades of this month?"));
int arrayList[] = {Integer.valueOf(grades)};
int arraysum;
arraysum = arrayListGetFirstIndex + arrayListGetSecondIndex + ...; //Extracts all of the indices and adds them up?
int calculation;
calculation = arraysum / arrayListAmmountOfNumbersInTheList; //An example of how it go about working


This would be a suitable solution too:

String[] input = JOptionPane.showInputDialog("What are your grades of this month?").split(" ");
        double[] grades = new double[input.length];
        double average = 0.0;
        for (int i = 0; i < input.length; i++) {
            // Note that this is assuming valid input
            grades[i] = Double.parseDouble(input[i]);
        average /= grades.length;

So you could type in multiple "grades" seperated by a whitespace.