In: Computer Science
Write Java code that allows a user to repeatedly enter numbers. Each time the user enters a number, the program should print out the average of the last 3 numbers (or all numbers if 3 or less have been entered). I would like a detailed explanation so that a beginner level Java programmer could understand.
code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
//declare a scanner variable to take user input
Scanner sc = new Scanner(System.in);
int a=0,b=0,c=0,sum=0,count=0;
double avg;
//take user input untill -1 entered
/*
repeatedly ask for 3 numbers in a loop, and exit if any input is -1;
and subtract the last entered number in next loop and get next number and find average
*/
while (true){
//let's say we have taken a, b, c => 3 inputs,
//sum variable will be , sum = a+b+c, avg = sum /3;
//while repeats again, now we take 4th input, let's say it as a2,
//now, we need to subtract a from sum and add a2 to it ,
// sum = sum -a, sum = sum+a2, which means sum(b+c+a2), and find new average
sum -= a;
System.out.println("Enter number (-1 to exit): ");
a = sc.nextInt();
if(a == -1) break;
sum += a;
if(count < 3)
avg = (double)sum/1;
else
avg = (double)sum/3;
System.out.printf("Average : %.2f\n",avg);
sum -= b;
System.out.println("Enter number (-1 to exit): ");
b = sc.nextInt();
if(b == -1) break;
sum += b;
if(count < 3)
avg = (double)sum/2;
else
avg = (double)sum/3;
System.out.printf("Average : %.2f\n",avg);
sum -= c;
System.out.println("Enter number (-1 to exit): ");
c = sc.nextInt();
if(c == -1) break;
sum += c;
avg = (double)sum/3;
System.out.printf("Average : %.2f\n",avg);
count += 3;
}
}
}