I've just started learning Java, and I'm pretty confused at this point. I'm trying to make a program that will average out any amount of numbers that the user would input, but I can't figure out how to allow the user to input as many numbers as they want. Right now, the code just lets them do 1 number before it averages.
Notes: There's a good chance I'm writing this totally wrong, I'm doing this to see what I know so far
I use Eclipse
I'm learning from www.thenewboston.org
Here's 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;
}
}
You can use a LinkedList<Double>
and a loop to let the user input an artificial amount 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 like and then enter some text like "done"
.