[英]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.