Answer:
import java.util.Scanner;
public class DistanceFromAverage
{
static double[] userValues = new double[20];
static double userInput;
static int totalValues = 1;
static int y = 0;
static double totalUserInput = 0;
static double avg;
public static void main(String[] args)
{
getInfoFromUser();
calculation();
}
public static void getInfoFromUser() {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer or enter 99999 to quit: ");
userInput = Double.parseDouble(input.nextLine());
if(userInput == 99999)
System.out.println("Enter a value: ");
while(userInput != 99999 && totalValues < userValues.length)
{
userValues[totalValues] = userInput;
totalUserInput = totalUserInput + userInput;
System.out.print("Enter an integer or enter 99999 to quit: ");
userInput = Double.parseDouble(input.nextLine());
if(userInput == 99999)
break;
totalValues++;
}
}
public static void calculation() {
avg = totalUserInput / totalValues;
System.out.println("You have entered " + totalValues + " numbers and their avg is " +avg);
for (y = 1; y < totalValues; ++y)
{
System.out.println(userValues[y] + " is " + (userValues[y] - avg) + " away from the avg");
}
}
}
Step-by-step explanation:
- Create the getInfoFromUser method that takes information from the user and save it in the array and if user enters 99999 then it exits
- Stop taking information from user if it exceeds 20 inputs.
- Create the calculation method that finds the average and as well as calculates the distance from the average.
- Calculate the average by using the following formula:
avg = totalUserInput / totalValues
- At the end, display all the results.