write a program that calculates the average of N integers. The program should pr
ID: 3624031 • Letter: W
Question
write a program that calculates the average of N integers. The program should prompt the user to enter the value of N and then afterward must enter all N numbers.If the user enters a non positive value for N, then an exception should be thrown with the message " N must be positive." if there is exception as the user is entering the N numbers, an error message should be displayed and the user prompted to enter the number again.
I've tried coding it myself and this is what I came up with. If you can help me make it work like it should I'd appreciate it. My code compiles, however, it's not doing what I want.
Thanks.
public class program3JS
{
public static void main (String[] args)
{
// Variable declarations
int n = 0;
boolean error = true;
double average;
int sum = 0;
int num;
char ch;
Scanner keyboard = new Scanner(System.in);
// Loop until there is no error
do
{
try
{
error = false;
System.out.println("How many numbers do you want to enter?");
n = keyboard.nextInt();
if (n < 0 )
throw new Exception ("Number must be greater than 0.");
}
catch (Exception e)
{
String message = e.getMessage();
System.out.println(message);
System.exit(0);
}
}
while (error);
// Loop through each number and calculate the average
int i;
for (i = 0; i < n; i ++)
{
// Repeat input as long as there is an error
do
{
try
{
error = false;
System.out.println("Enter number " + (i+1));
num = keyboard.nextInt();
sum += num;
if (num != ch)
throw new Exception ("Error, please enter number again");
}
catch (Exception e)
{
String message = e.getMessage();
System.out.println(message);
}
}
while (error);
}
average = sum/i;
System.out.println ("The average is " + average);
}
}
Explanation / Answer
import java.util.Scanner;
public class Pythagoras {
public static void main (String[] args)
{
// Variable declarations
int n = 0;
boolean error = true;
double average;
int sum = 0;
int num;
Scanner keyboard = new Scanner(System.in);
// Loop until there is no error
do
{
try
{
error = false;
System.out.println("How many numbers do you want to enter?");
n = keyboard.nextInt();
if (n < 0 )
throw new Exception ("Number must be greater than 0.");
}
catch (Exception e)
{
String message = e.getMessage();
System.out.println(message);
System.exit(0);
}
}while(error);
int i;
// Loop through each number and calculate the average
for (i = 0; i < n; i ++)
{
// Repeat input as long as there is an error
System.out.println("Enter Number " + (i+1));
num = keyboard.nextInt();
while(num<0)
{
System.out.println("Negative Numbers are not Allowd please Enter Number" + (i+1)+ " Again :");
num = keyboard.nextInt();
}
sum = sum+num;
}
average = sum/(double)i;
System.out.println ("The average is " + average);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.