[英]Array Only Returning Most Recent Input
所以我試圖將數組作為參數傳遞給 class 但當我打印到屏幕時它只顯示最新的對象輸入
for (int j=0;j<5;j++) {
do {
System.out.print("Enter Test Score " +(j+1)+" between 0-100 : ");
score = sc.nextInt();
sc.nextLine();
}while(score<0||score>100);
ts[j] = score;
}
s.setTestScore(ts);
System.out.println("");
這就是它應該完成的方式,我沒有正確地將它傳遞給它應該是數組中的 position 和得分的方法,而我只是反復通過最近的得分
for (int j=0;j<5;j++) {
//Prints this message to the screen to make sure score is between 0-100
do {
System.out.print("Enter Test Score " +(j+1)+" between 0-100 : ");
score = sc.nextInt();
sc.nextLine();
}while(score<0||score>100);
s.setTestScore(j,score);
}
當我傳遞名稱和 ID 時,它使用完全相同的系統 s.set(nameofmethod)
void setTestScore(int[] test) {
this.test = test;
}
int[] getTests() {
return test;
}
然后我將測試傳遞給一個計算方法,它只打印出每個 object 創建的通過/失敗,無論分數如何
void calculateResult() {
int sum = 0;
for(int i = 0; i < test.length; i++){
sum += test[i];
}
sum = sum/numTests;
if(sum<40) {
grade = "Fail";
}
else {
grade = "Pass";
}
System.out.println(grade);
}
我認為您要么需要在輸入每個學生的考試成績后運行 calculateResult,要么需要某種 hash 的 arrays 來跟蹤哪個考試成績數組屬於哪個學生。 由於您只有一個數組test[]
,學生 id 5 的分數被學生 id 77 的分數覆蓋。您可以嘗試這樣的事情:
for (int j=0;j<5;j++) {
do {
System.out.print("Enter Test Score " +(j+1)+" between 0-100 : ");
score = sc.nextInt();
sc.nextLine();
}while(score<0||score>100);
ts[j] = score;
}
s.setTestScore(ts);
s.calculateResult();
System.out.println("");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.