2014-02-09 58 views
0

你能給我一個提示,我在做什麼錯在我的平均方法的平均值?我試圖在讀取的分數中調用該方法。我試圖獲得我在input.txt文件中的平均分數。平均方法數組提示

import java.io.*; 
import java.util.*; 
public class FindGrade { 
public static final int NUM_SCORE_TYPES = 5; 

public static void main(String[] args) { 
    Scanner scan = null; 
    int[] quizArray = null;  
    int[] labArray = null;  
    int[] attendance = null; 
    int[] midterms = null; 
    int quizgrade =0; 
    int labgrade=0; 
    int attendance_1=0; 
    int midterms_1 =0; 
    String name; 


    try { 
     scan = new Scanner(new File("input.txt")); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
     return; 
    } 

    // each iteration is for single exam type (ie: Quizzes is the 1st one) 
    for (int i = 0; i < NUM_SCORE_TYPES; i++) { 

     name = scan.next(); 
     int numScores = scan.nextInt(); 
     int maxGrade = scan.nextInt(); 

     if (name.equals("Quizzes")) { 
      quizArray = new int[numScores]; 
      readScores(quizArray, numScores, scan); 


     } 

     else if (name.equals("Labs")) { 
      labArray = new int[numScores]; 
      readScores(labArray, numScores, scan); 

     } 
     else if (name.equals("Lab_attendance")) { 
      attendance = new int[numScores]; 
      readScores(attendance, numScores, scan); 

     } 
     else if (name.equals("Midterms")) { 
      midterms = new int[numScores]; 
      readScores(midterms, numScores, scan); 

     } 

    } 

} 


public static void readScores(int[] scoreArray, int numScores, Scanner scan) { 
    for (int i = 0; i < numScores; i++) { 
     scoreArray[i] = scan.nextInt(); 
    } 
} 

public static void average(double [] scoreArray, int numScores){ 
    double sum=0; 
    for(int i=0; i< scoreArray.length; i++){ 
     sum += scoreArray[i]; 
    } 
    double average = sum/numScores; 

    System.out.println(sum + " " + average); 



} 
+0

什麼是你的堆棧跟蹤? – hichris123

+0

對不起,我是一個初學者,我不熟悉術語stacktrace。 – user124557

+0

你得到的錯誤是什麼? (Stacktrace是Java提供的錯誤日誌,基本上是 – hichris123

回答

1

無論如何,您不能直接使用您在那裏創建的數組來調用它。由於陣列的類型爲int,但平均方法需要double陣列。當你改變這個,你可以調用這樣的方法...

public static void readScores(int[] scoreArray, int numScores, Scanner scan) { 
    for (int i = 0; i < numScores; i++) { 
     scoreArray[i] = scan.nextInt(); 
    } 

    average(scoreArray, numScores); // <----- Call it here 
} 

public static void average(int[] scoreArray, int numScores){ 
    double sum=0; 
    for(int i=0; i< scoreArray.length; i++){ 
     sum += scoreArray[i]; 
    } 
    double average = sum/numScores; 
    System.out.println(sum + " " + average); 
} 
+0

謝謝,我能夠得到它 – user124557