我是一名初学Java程序员,编写一个程序来计算一组正整数的平均值。首先,它向用户查询要输入的整数量。然后,它从用户收集整数并输出计算的平均值。我在处理例外方面遇到了麻烦。当用户尝试输入要进行平均的负数时,会正确显示异常,但它不能正确地继续for循环以收集适当数量的数字。例如,下面是一个示例输出:
Please enter the number of integers to be averaged: 5
Enter a number: 1
Enter a number: 2
Enter a number: -3
NegativeIntegerException: N must be a positive integer.
Enter a number: 3
Enter a number: 4
The average is: 0.0
它正确抛出异常,但没有继续填充5个整数。只有其他4个有效。
以下是代码:
import java.util.*;
class NegativeIntegerException extends Exception {
public NegativeIntegerException()
{
super("N must be a positive integer.");
}
}
public class intAverage {
public static void main(String[] args)
{
int N = 0; //number of integers to be averaged
int[] numbers = null; //array to hold integers
int sum = 0;
int newInt;
double average;
Scanner keyboard = new Scanner(System.in);
int x = 1; //for do-while loop #1
int z = 1; //for do-while loop #2
do {
try {
System.out.print("Please enter the number of integers to be averaged: ");
N = keyboard.nextInt();
numbers = new int[N]; //setting size of array
x = 2;
}
catch (Exception e) {
System.out.println("N must be a positive integer");
}
} while (x == 1);
do {
for(int i = 0; i < N; i++) //collecting the integers
{
System.out.print("Enter a number: ");
newInt = keyboard.nextInt();
if (newInt < 0) {
try {
throw new NegativeIntegerException();
}
catch(NegativeIntegerException e) {
System.out.println(e);
}
}
newInt = numbers[i];
}
z = 2;
} while (z == 1);
for(int y = 0; y < N; y++) //calculate average
{
sum = sum + numbers[y];
}
average = sum / N;
System.out.println("The average is: " + average);
}
}
答案 0 :(得分:3)
打印出异常时,从i中减1,然后继续。这基本上会重启迭代。
do {
for(int i = 0; i < N; i++) //collecting the integers
{
System.out.print("Enter a number: ");
newInt = keyboard.nextInt();
if (newInt < 0) {
try {
throw new NegativeIntegerException();
}
catch(NegativeIntegerException e) {
System.out.println(e);
// Ignore this input
i--;
continue;
}
}
numbers[i] = newInt;
}
z = 2;
} while (z == 1);
请注意,您不需要为此工作抛出异常 - 您可以轻松地说:
do {
for(int i = 0; i < N; i++) //collecting the integers
{
System.out.print("Enter a number: ");
newInt = keyboard.nextInt();
if (newInt < 0) {
System.out.println("NegativeIntegerException: N must be a positive integer");
// Ignore this input
i--;
continue;
}
numbers[i] = newInt;
}
z = 2;
} while (z == 1);
这也更具可读性。