2017-05-15 77 views
0

在我的java類中,我們開始編寫方法,而不是將所有代碼放在主要方法中。問題集中的問題之一是「編寫一個方法,詢問用戶他們已經學習的課程數量n然後該方法將要求在這些課程中獲得的n等級並返回平均」。這是我到目前爲止有:需要從一組用戶的成績中獲得平均值

import java.util.*; 

    public class MethodPracticeSet2 
    {public static int average() 
    { 
    //Create new Scanner object 
    Scanner sc=new Scanner(System.in); 

    //Create divisor variable 
    int divisor=0; 

    //Ask user for their course 
    System.out.println("How many courses are you currently in?"); 
    int course =sc.nextInt(); 
    for (int i=0; i<course; i++) 
    { 
     System.out.println("What are your grades for those courses?"); 
     int grades[]= new int[i]; 
     grades[i]=sc.nextInt(); 
     divisor= divisor+i; 
    } 
    System.out.println("Your average for these courses is "+divisor/course); 
    return average(); 
    } 

    public static void main(String[] args) 
    { 
     int output=average(); 
     System.out.println(output); 
    } 

    } 

輸出詢問課程的用戶在數量,然後要求的等級,然後輸出如下:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 
    at MethodPracticeSet2.average(MethodPracticeSet2.java:24) 
    at MethodPracticeSet2.main(MethodPracticeSet2.java:33) 

任何幫助將是巨大的!

+0

嘗試使用正確的縮進。 – sia

回答

0

首先,您需要在之前聲明您的數組循環。目前,你正在循環的每次迭代中創建一個新的數組,這顯然不是你想要做的;這也是你得到ArrayIndexOutOfBoundsException的原因,原因是當你用i作爲0實例化陣列時,你試圖存儲一個數字到空的數組中,因此是例外。


這是你應該如何聲明數組:

int grades[] = new int[course]; 

for (int i = 0; i < grades.length; i++) 
{ 
    System.out.println("What are your grades for those courses?"); 
    grades[i] = sc.nextInt(); 
    divisor += 1; 
} 

然後返回那些成績一般,你可以這樣做:

int totalGrades = 0; 

for(int grade : grades){ 
    totalGrades += grade; 
} 
System.out.println("Your average for these courses is "+totalGrades/divisor); 
return totalGrades/divisor; 
+0

謝謝!這一個爲我工作得很好 –

0

試試這個:

public class MethodPracticeSet2 { 
public static int average() { 
    // Create new Scanner object 
    Scanner sc = new Scanner(System.in); 

    // Create divisor variable 
    int divisor = 0; 

    // Ask user for their course 
    System.out.println("How many courses are you currently in?"); 
    int course = sc.nextInt(); 
    System.out.println("What are your grades for those courses?"); 
    int sum = 0; 
    for (int i = 0; i < course; i++) { 
     sum += sc.nextInt(); 
    } 
    System.out.println("Your average for these courses is " + (float) sum/course); 
    return average(); 
} 

public static void main(String[] args) { 
    int output = average(); 
    System.out.println(output); 
} 

}

+0

只解決IndexOutOfBounds症狀。沒有解決實際問題。 BTW:遞歸調用是OP的,不在這裏介紹。 –