我收到java.lang.ArrayIndexOutOfBoundsException错误。
public class Trainee implements EvaluationDetails
{
private int traineeId;
private String traineeName;
private double traineeMarks[];
public Trainee(int id,String name,double Marks[])
{
traineeId=id;
traineeName=name;
traineeMarks=Marks;
}
public int getTraineeId()
{
return traineeId;
}
public String getTraineeName()
{
return traineeName;
}
public boolean validateTraineeMarks()
{
if(noOfCourses>0 && noOfCourses<8)
{
for(int i=0;i<=traineeMarks.length;i++)
{
if(traineeMarks[i]>0 && traineeMarks[i]<100)
continue;
else
return false;
}
return true;
}
else
return false;
}
public double calculateGPA()
{
int GPA;
int Cp[]=new int[7];
boolean bool=validateTraineeMarks();
if(bool==true)
{
for(int i=0;i<traineeMarks.length;i++)
{
if(traineeMarks[i]>=85 && traineeMarks[i]<=100)
Cp[i] = 5;
else if(traineeMarks[i]>=65 && traineeMarks[i]<85)
Cp[i] = 4;
else if(traineeMarks[i]>=0 && traineeMarks[i]<=65)
Cp[i] = 3;
}
GPA = //GPA calculation logic
}
else
{
System.out.println("Improper values for trainee marks");
return 0.0;
}
return GPA;
}
}
主要课程如下所示:
public class Demo {
public static void main(String[] args)
{
double marks[]={74.0,57.0,86.0,93.0,56.0,73.5,83.0};
Trainee t = new Trainee(102,"Dixon",marks);
System.out.println("Trainee Id:"+t.getTraineeId());
System.out.println("Trainee Name:"+t.getTraineeName());
System.out.println("GPA is"+t.calculateGPA());
}
}
接口编码如下:
public interface EvaluationDetails
{
int creditpoints[]={3,3,4,4,2,3,5};
int noOfCourses=7;
public double calculateGPA();
}
答案 0 :(得分:4)
for(int i=0;i<=traineeMarks.length;i++)
应为for(int i=0;i<traineeMarks.length;i++)
问题是你正在尝试访问array.length + 1 elemnt
答案 1 :(得分:1)
你的错误在这里:
for(int i=0;i<=traineeMarks.length;i++)
java中的索引(以及所有类似c的语言)从0开始,因此数组的最后一个索引是length-1
。因此,修复您的循环定义如下:
for(int i=0;i<traineeMarks.length;i++)
答案 2 :(得分:0)
这是你的错误:
for(int i=0;i<=traineeMarks.length;i++)
你应该从i=0
转到traineeMarks.length-1
所以,
for(int i=0;i<traineeMarks.length;i++)
答案 3 :(得分:0)
for(int i = 0; i&lt; = traineeMarks.length; i ++)
应该是
for(int i = 0; i&lt; traineeMarks.length; i ++)
答案 4 :(得分:0)
for(int i=0;i<=traineeMarks.length;i++) //this is wrong this cause to java.lang.ArrayIndexOutOfBoundsException
使用
for(int i=0;i<traineeMarks.length;i++)