在我的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)
任何帮助将是巨大的!
尝试使用正确的缩进。 – sia