I have a method outside of the main method that averages. At the end of the main I am calling on that averaging method. I am not understaning the propper way to 1. use variables I declare with other methods in this program. for example the sum which is defined in the calculate_average method. or The sum which is defined in the main method.
Please show me
how to interchange variables in and out of the main method. interchangeably between methods that are not in main.
call on a method outside of main in main to calculate the average.
Here is my current code.
import java.util.ArrayList; import java.util.Scanner; class programTwo { private static Double calculate_average( ArrayList<Double> myArr ) { Double Sum = 0.0; for (Double number: myArr) { Sum += number; } } public static void main( String[] args ) { Scanner scan = new Scanner(System.in); ArrayList<Double> myArr = new ArrayList<Double>(); double Sum = 0; int count = 0; System.out.println("Enter a number to be averaged, repeat up to 20 times:"); String inputs = scan.nextLine(); while (!inputs.matches("[qQ]") ) { if (count == 20) { System.out.println("You entered more than 20 numbers, you suck!"); break; } Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input myArr.add(scan2.nextDouble()); count += 1; System.out.println("Please enter another number or press Q for your average"); inputs = scan.nextLine(); } Double average = calculate_average(myArr); System.out.println("Your average is: " + average); return Sum / myArr.size(); }}