Average estimated program problem

I just started learning Java, and I'm pretty confused at this point. I am trying to make a program in which any number of numbers the user will enter will be calculated, but I cannot figure out how to allow the user to enter as many numbers as they want. Right now, the code just allows them to make 1 number before it becomes average.

Notes: There is a good chance, I am writing this completely wrong, I am doing this to find out what I still know

I am using eclipse

I study at www.thenewboston.org

Here is the code:

import java.util.Scanner; class MainClass { public static void main(String[] args){ System.out.println("Enter Grades Now"); Scanner input = new Scanner(System.in); double input2 = input.nextDouble(); System.out.println(average(input2)); } public static double average(double...numbers){ double total=0; for(double x:numbers) total+=x; return total/numbers.length; } } 
+4
source share
4 answers

You can use the LinkedList<Double> and loop to let the user enter an artificial number of numbers.

 Scanner input = new Scanner(System.in); List<Double> allDoubles = new LinkedList<Double>(); do { System.out.print("Next grade: "); allDoubles.add(input.nextDouble()); } while (input.hasNextDouble()); System.out.println(average(allDoubles.toArray(new Double[0]))); 

Enter as many values ​​as you want, and then enter text, such as "done" .

+3
source

You need a loop to take all the values. A List to save them is also useful:

  public static void main(String[] args){ System.out.println("Enter Grades Now:"); List<Double> inputs = new ArrayList<Double>(); Scanner input = new Scanner(System.in); while(input.hasNextDouble()){ inputs.add(input.nextDouble()); //add values to the list } } System.out.println(average(inputs)); } public static double average(List<Double> numbers){ double total=0; for(Double x:numbers) total+=x; return total/numbers.size(); } 
+1
source
 ArrayList<Double> al = new ArrayList<Double>(); while(input.hasNextDouble){ al.add(input.nextDouble()) System.out.print("Prompt: "); //ask for input here } // average the elements in the arraylist 
+1
source

You can suggest the user to enter numbers, separating them with spaces:

 Scanner input = new Scanner(System.in); String userInput = input.nextline(); // eg "12 23 34" String[] stringArray = userInput.split(" "); Double[] doubleArray = new Double[stringArray.length]; // converting string array to double array for (int i = 0; i < stringArray.length; ++) { doubleArray[i] = Double.parseDouble(stringArray[i]); } System.out.println(average(doubleArray)); 
+1
source

All Articles