gpt4 book ai didi

java - 数组输入未相加。 -- 总计 += ScoreArray[i];

转载 作者:行者123 更新时间:2023-12-02 08:57:43 24 4
gpt4 key购买 nike

由于某种原因,下面的这部分代码没有将每个数组项添加到一起。我单步执行调试器,正在创建并递增数组项,但 total += ScoreArray[i]; 似乎没有将已输入的数字相加。相反,我只是将第一个输入除以数组长度作为最终输出

    public double getAverage()
{
double total = 0.0;
for (int i = 0; i < scoreArray.length; i++)
total += scoreArray[i];

return (total / scoreArray.length);
}

完整代码

package driver;
import java.util.Scanner;

public class TestScores
{
private double[] scoreArray;

public TestScores(double[] test) throws IllegalArgumentException
{
scoreArray = new double[test.length];
for (int i = 0; i < test.length; i++)
{
if (test[i] < 0 || test[i] > 100)
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();
}

TestScores testScore = new TestScores(scoreArray);
System.out.println(testScore.getAverage());
}
}

最佳答案

请更改接受用户评分的循环,如下所示:

for (int i = 0; i <= score - 1; i++)
{
System.out.print("Enter test score " + (i + 1)+ ": ");
// scoreArray[scores] = userInput.nextDouble(); <-- value of scores is zero
scoreArray[i] = userInput.nextDouble();
}

在填充 ScoreArray 时,您应该使用“i”而不是“scores”。目前,您仅使用最后输入的用户输入来填充“scoreArray”。

关于java - 数组输入未相加。 -- 总计 += ScoreArray[i];,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60387746/

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