gpt4 book ai didi

java - 寻找退出系统或停止代码的方法

转载 作者:行者123 更新时间:2023-12-01 18:14:20 26 4
gpt4 key购买 nike

下面的当前代码会在输入越界输入时导致错误发生,然后将错误打印到屏幕上,这就是我想要的。但问题是,代码出错后,它仍然打印答案,而不是停止。我尝试在消息下方的 if 代码中放入系统退出语句,但随后 IDE 提醒我,由于某种原因,else 需要一个“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];
}

关于java - 寻找退出系统或停止代码的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60404580/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com