gpt4 book ai didi

java - 如何将数组传递给另一个类

转载 作者:行者123 更新时间:2023-12-01 23:13:00 26 4
gpt4 key购买 nike

我正在编写一个测验分数程序,我在主方法中有数组,我需要在单独的类“addQuizScore(int Score)”、“getTotalScore”中提供适当的构造函数和方法。我对 Java 还很陌生,并且不知道如何正确地做到这一点。

import java.util.*;

public class StudentQuiz
{
public static void main(String[] args)
{

int [] score = {7,8,5,6,0,10,7,6};

StudentQuizInfo newStudent = new StudentQuizInfo(score);

System.out.println("total score: " +newStudent.getTotalScore());

}
}


import java.util.*;
public class StudentQuizInfo {

private int overallScore = 0;
private int totalScore = 0;


public StudentQuizInfo(int[] score) {
}

public int addQuizScore(int [] score)
{
int k;
int overallScore = 0;
for(k = 0; k <score.length; k++)
{
overallScore = overallScore + score[k];
}
return overallScore;
}

int getTotalScore()
{
int totalScore = overallScore;
return totalScore;
}
}

ATM 代码打印 totalscore: 0 这是不正确的。

我意识到我当前的代码非常糟糕,因此任何有关如何纠正此问题的指示都将非常感激,特别是关于如何正确使用 addQuizScore 的指示。谢谢

最佳答案

添加

newStudent.addQuizScore(score);

之后

StudentQuizInfo newStudent = new StudentQuizInfo(score);

应该可以解决问题。

此外,您的架构有点奇怪。您的构造函数按照现在编写的方式没有执行任何操作。由于您有一个名为 addQuizScore 的方法,我假设您不需要将分数保留在 StudentQuizInfo 对象中,因此您可以安全地删除 int来自类的构造函数的 [] Score 参数。

此外,变量 overallCoretotalScore 似乎是多余的。

关于java - 如何将数组传递给另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21578736/

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