82.9k views
5 votes
Statistics are often calculated with varying amounts of input data. Write a program that takes any number of non-negative integers as input, and outputs the average and max. A negative integer ends the input and is not included in the statistics. Ex: If the input is: 15 20 0 5 -1 the output is: 10 20

1 Answer

4 votes

Answer:

Explanation:

import java.util.Scanner;

public class LabProgram

{

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);//to read input

int count=0;//to keep track of the count of numbers entered

int max=0;//to store the maximum value

int sum=0;//to store the sum of numbers entered

double av=0;//to calculate and store the average

//reading inputs until a negative number is entered

while(true)

{

int n = sc.nextInt();//reading input

if(n<0)//if negative number

break;//then stopping loop

count++;//increasing count

if(count==1)//means it is first number

max=n;

else if(max<n)//if current number is greater than previous max

max=n;//updating max

sum+=n;//adding new number to sum

}

//finding average

av = (double)sum/count;

//displaying output

System.out.println((int)av+" "+max);//remove type casting (int) here, if you want decimal places also

}

}

output:

15 20 0 5 -1

10 20

User Glcheetham
by
6.0k points