[英]How to pass an array to another class
我正在编写一个测验分数程序,我的主方法中有数组,我需要在单独的类“ 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;
}
}
自动柜员机代码打印totalscore: 0
,这是不正确的。
我意识到我当前的代码非常糟糕,因此,任何有关如何纠正此问题的指针将不胜感激,尤其是在如何正确使用addQuizScore方面。 谢谢
新增中
newStudent.addQuizScore(score);
后
StudentQuizInfo newStudent = new StudentQuizInfo(score);
应该解决问题。
此外,您的体系结构有点奇怪。 您的构造函数没有像现在这样编写任何内容。 我假设您拥有一个名为addQuizScore
的方法,因此无需将成绩保留在StudentQuizInfo
对象内,因此可以安全地从类的构造函数中删除int[] score
参数。
同样,变量overallCore
和totalScore
似乎是多余的。
像这样更改构造函数
public StudentQuizInfo(int[] score) {
addQuizScore(score)
}
要么
StudentQuizInfo newStudent = new StudentQuizInfo(score);
newStudent.addQuizScore(score);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.