i'm a new java user i'm having problems with my program using the try and catch
Dear someone who can help
This program is supposed to calculate the average of N integers. The
program should prompt the user to enter the value for N and then
afterword ,ist emter all N numbers. If the user enters a non- positive
value for N then an exception should be thrown (and caught) with the
message "N must be positive. If there is any exceptiono as the user is
entering the N numbers an error message should be displayed and the
user prompted to enter the number again.
The problem that i'm having is that when a negative number is entered
the message displays that it must be greater than 0 but the compiler
goes back to the c prompt instead of asking for another number. and if
anything other than a number is entered such as a letter the compiler
puts out the message null and goes to the c prompt and it's supposed to
say please enter a number again
I would appreciate some help or suggestions
// Author: Judith Spurlock
// Course: ITSE 2417
// Program No: 3
// Due Date: 10/20/2006
//
// Program Name: program3JS.java
import java.util.Scanner;
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);
}
}