在我的java类中,我们开始编写方法,而不是将所有代码放在main方法中。问题集中的一个问题是“编写一个方法,询问用户他们已经采取的课程数量 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 :(得分: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;
答案 1 :(得分: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);
}
}