2016-02-12 69 views
0

我要創建需要用戶輸入的基礎上檔次的學生的名字,用戶輸入了代碼。如何解決我的櫃檯和平均計算器

輸入是停止時的數小於0被輸入和輸出應爲學生姓名,總的所有分數和平均得分。

出於某種原因,我不能讓我的學生班級平均或打印總,我的計數器顯示錯誤「刪除此令牌「++」

這裏是我的主類,和我學生類:

/** 
* COSC 210-001 Assignment 2 
* Prog2.java 
* 
* description 
* 
* @author Tristan Shumaker 
*/ 
import java.util.Scanner; 

public class main { 

    public static void main(String[] args) { 
     double[] addQuiz = new double[99]; 
     int counter = 0; 
     //Creates new scanner for input 
     Scanner in = new Scanner(System.in); 

     //Prompts the user for the student name 
     System.out.print("Enter Student Name: "); 
     String name = in.nextLine(); 

     // requests first score and primes loop 
     System.out.print("Enter Student Score: "); 
     int scoreInput = in.nextInt(); 

     while(scoreInput >= 0) { 
      System.out.print("Enter Student Score: "); 
      scoreInput = in.nextInt(); 
      counter++; 
     } 
     System.out.println(); 
     System.out.println("Student name: " + name); 
     System.out.printf("\nAverage: %1.2f", total(addQuiz, counter)); 
     System.out.printf("\nAverage: %1.2f", average(addQuiz, counter)); 
    } 
} 

和我的學生類:

public class Student { 
    private String name; 
    private int total; 
    private int counter; 

    public Student() { 
     super(); 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public int getTotal() { 
     return total; 
    } 

    public void setTotal(int total) { 
     this.total = total; 
    } 

    public void addQuiz(int scoreInput) { 
     total += scoreInput; 
     int counter++; 
    } 

    public static double average(double[] addQuiz, int counter) { 
     double sum = 0; 
     for(int t = 0; t < counter; t++) { 
      sum += addQuiz[t]; 
     } 
     return (double) sum/counter; 
    } 
} 

任何幫助你們能夠給將不勝感激,感謝先進。

回答

0

addQuiz()方法只是counter++;變化int counter++;,否則你要申報與標識符counter++一個變量,它是不是一個有效的標識符。此外,由於你已經聲明average()要對Student類的靜態方法,你將需要調用它像這樣:

Student.average(addQuiz, counter); 

我不是在你的代碼看到了total()的定義,所以我不知道這是否也適用於此。

編輯

要回答爲什麼average()將返回零,它看起來像你從來沒有設置您傳遞的,所以它會包含所有零的addQuiz雙陣列中的任意值,並且結果sum爲0。我想想要做的是改變你的while循環的主要方法把scoreInput值數組中的counter指數像這樣:

while(scoreInput >= 0) { 
    System.out.print("Enter Student Score: "); 
    scoreInput = in.nextInt(); 
    addQuiz[counter] = scoreInput; 
    counter++; 
} 
+0

非常感謝。這是一個錯誤,我看了一百次,沒有注意到。 – theshu

+0

'addQuiz'是'Student'的一種方法 –

+0

@ScaryWombat是的它是;它包含一個錯誤(OP詢問)。在調用'average()'方法時,它也是OP主類中的雙數組...你想說什麼? – jonk

0

在你的主課中,你根本沒有使用Student課。

考慮做

Student student = new Student (name); 

,然後使用方法,如

student.addQuiz (scoreInput); 

後來

student.getTotal(); 

你也不需要存儲變量counterStudent對象因爲它被作爲參數傳遞。

+0

好吧,我想我理解你說的話我會試圖弄清楚它的概念。謝謝 – theshu