gpt4 book ai didi

java - 如何修复我的脚本以按正确顺序运行?

转载 作者:行者123 更新时间:2023-12-02 10:37:59 24 4
gpt4 key购买 nike

程序应该返回

The test scores in descending order are: (Scores) The average is (average)

我收到的结果是

The average is (average) The test scores in descending order are: (Scores)

如何修复它以获得正确的返回

import java.util.Scanner;

public class Average
{
private int[] data;
private double mean;

public Average()
{
data = new int[5];
int number = 0;
int Temp = 0;
String[] Scores = new String[5];
Scanner keyboard = new Scanner(System.in);

for(int index = 0; index < data.length; index++)
{
number++;
System.out.print("Enter test score #" + number + ":");
Temp = keyboard.nextInt();
data[index] = Temp;
}

selectionSort();
calculateMean();
}

public void selectionSort()
{
int n = data.length;

for(int index = 0; index < n-1; index++)
{
int min_idx = index;
for(int j = index+1; j < n; j++)
if(data[j] >= data[min_idx])
min_idx = j;

int temp = data[min_idx];
data[min_idx] = data[index];
data[index] = temp;
}
}

public String toString()
{
String MyScore = "Your test scores in descending order are: " + "\n";

for(int index = 0; index < data.length; index++)
{
MyScore += data[index] + " ";
}
return MyScore;
}

public void calculateMean()
{
int Sum = 0;
int Mean = 0;

for(int index = 0; index < data.length; index++)
{
Sum += data[index];
}
Mean = Sum/data.length;
System.out.println("The average is " + mean);
}
}

为了使这项工作成功,我必须交换什么?

编辑:此文件中使用了 Average 类

public class AverageDriver
{
public static void main(String[] args)
{
Average MyScores = new Average();
System.out.print(MyScores);
}
}

最佳答案

您应该仅在调用 toString() 之后调用 calculateMean()
所以你可以修改构造函数

selectionSort();
System.out.println(toString());
calculateMean();

或仅在构造函数中调用 selectionSort();,然后在 main 中调用

public class AverageDriver
{
public static void main(String[] args)
{
Average myScores = new Average();
System.out.print(myScores);
myScores.calculateMean();
}
}

顺便说一句,你应该使用小写的变量名称,这将修复 calculateMean() 中的错误:你正在调用 System.out.println("Theaverage is "+ Mean); 但变量是 Mean

关于java - 如何修复我的脚本以按正确顺序运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53139641/

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