Simple averaging program with for loops

0 jack barnes · November 7, 2015
Hi, I'm currently in the AP CS class at my highschool and we were given a short answer problem to do at home.
We have to make a program that asks the user how many values they'd like to input, then to loop the amount whilst asking them what value, and finally average the values.
Heres what I have so far.
int val;
Scanner scan = new Scanner(System.in);
System.out.println("How many values would you like to input?");
val = scan.nextInt();
for (int i = 0; i < val; i++){
    System.out.println("Enter your number:");
}

I don't know how I'd save all the numbers they enter to average them.
Please help!

Post a Reply

Replies

Oldest  Newest  Rating
0 Yang Li · November 9, 2015
int val;
int sum = 0;
int operand = 0;
Scanner scan = new Scanner(System.in);
System.out.println("How many values would you like to input?");
val = scan.nextInt();
for (int i = 0; i < val; i++){
     System.out.println("Enter your number:");
     operand = scan.nextInt();
     sum = sum + operand;
}
System.out.println("The average is "+sum/val);
0 George Harutyunyan · November 9, 2015
After you ask the user to "Enter your number", make a new variable, such as "total" and take the users input again. But, instead of doing total = scanner.nextLine(), do total += scanner.nextLine(). What += does is the same thing as...

total = total + scanner.nextLine() which adds all the values as you progress. When you are done, simply divide total/val.
  • 1

Java / Android Development

107,314 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator