2017-05-15 56 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的,不在这里介绍。 –