正在寻找退出系统或停止代码的方法



当输入越界输入时,下面的当前代码导致错误跳闸,然后将错误打印到屏幕上,这正是我想要的。然而,问题是,在代码跳闸后,它仍然在打印答案,而不是停止。我试图在消息下的if代码中放入一个系统退出语句,但随后IDE提醒我,由于某种原因,其他代码需要一个"if"。有没有办法在代码打印到屏幕后停止所有功能

public Driver(double[] test) throws IllegalArgumentException
{
scoreArray = new double[test.length];
for (int i = 0; i < test.length; i++)
{
if (test[i] < 0 || test[i] > 100)
System.err.println("Test scores must have a value less than 100 and greater than 0.");
// throw new IllegalArgumentException("Test scores must have a value less than 100 and greater than 0.");
else
scoreArray[i] = test[i];
}
}

完整代码我使用的IDE是netbeans

package driver;
import java.util.Scanner;
import java.text.DecimalFormat; 

public class Driver
{
private double[] scoreArray;
public Driver(double[] test) throws IllegalArgumentException
{
scoreArray = new double[test.length];
for (int i = 0; i < test.length; i++)
{
if (test[i] < 0 || test[i] > 100)
System.err.println("Test scores must have a value less than 100 and greater than 0.");
// throw new IllegalArgumentException("Test scores must have a value less than 100 and greater than 0.");
else
scoreArray[i] = test[i];
}
}
public double getAverage()
{
double total = 0.0;
for (int i = 0; i < scoreArray.length; i++)
total += scoreArray[i];
return (total / scoreArray.length);
}
public static void main(String[] args)
{  
int score = 0;
// int scores = 0;
Scanner userInput = new Scanner(System.in);
System.out.print("Enter number of test scores:");
score = userInput.nextInt();
double[] scoreArray = new double[score];
for (int i = 0; i <= score - 1; i++)
{    
System.out.print("Enter test score " + (i + 1)+ ":");
//scoreArray[scores] = userInput.nextDouble();  
scoreArray[i] = userInput.nextDouble();
}
DecimalFormat ft = new DecimalFormat("####");
ft = new DecimalFormat("0.0"); 
Driver testScore  = new Driver(scoreArray);
//System.out.println(driver.getAverage);
System.out.println(ft.format(testScore.getAverage()));
}
}

如果要在一个if中放置两个语句,则需要在它们周围放置大括号{}。常见的智慧是总是在if语句中使用大括号。这就是为什么当您试图在ifelse之间添加另一条语句时,编译器告诉您这是一个错误。

像这样:

if (test[i] < 0 || test[i] > 100) {
System.err.println("Test scores must have a value less than 100 and greater than 0.");
throw new IllegalArgumentException("Test scores must have a value less than 100 and greater than 0.");
} else { 
scoreArray[i] = test[i];
} 

最新更新