Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create a new Java application called \"Averager\" (without the quotation marks)

ID: 3854422 • Letter: C

Question

Create a new Java application called "Averager" (without the quotation marks) to get positive integers (i.e., any integer greater than 0) from the user, each preceded with a suitable data entry prompt, until the user enters -1 (the sentinel). Use a do-while loop. Compute the average of the series of integers and print the average. Be sure to format the average with two decimal positions. Don't include the sentinel in calculation of the average. Include suitable data validations for invalid data (e.g. the user enters a letter instead of an integer), but stay in the loop until the sentinel is entered.

Explanation / Answer

import java.util.*;

class Avereger

{

public static void main (String[] args) throws java.lang.Exception

{

int i,counter,sum;

sum = counter = 0;

double avg;

Scanner input = new Scanner(System.in);

do

{

System.out.println(" Enter the integer : ");

while(!input.hasNextInt())

{ //repeat until a number is entered.

input.next();

System.out.println("Enter number only"); // validate

}

i = input.nextInt();

if(i == -1)

break;

else

{

counter++; //increment counter only if i != -1

sum = sum +i;

}

  

}while(i != 0);

avg = (double)sum/(double)counter;

System.out.printf(" Average = %.2f",avg);

}

}

Output:


Enter the integer : 4

Enter the integer : a
Enter number only 6

Enter the integer : 7

Enter the integer : 12

Enter the integer : 3

Enter the integer : -1

Average = 6.40

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote