为什么数组给出错误?
为什么在这里:arrayList = {firstName,lastName,ID,examValue,score};给出错误?该方法应该调用一个构造函数,它是Exam(String firstName,String lastName,int ID,String examType,int score),那么这个方法有什么问题?提前致谢!为什么数组给出错误?
public static Exam[] readAllExams(Scanner s)
{
Exam[] arrayList = null;
String firstName = "";
String lastName = "";
int ID = 0;
String examValue = "";
int score = 0;
while(s.hasNext())
{
if(s.hasNextLine())
{
firstName = s.next();
lastName = s.next();
}
else if(s.hasNextInt())
{
ID = s.nextInt();
}
else if (s.hasNextLine())
{
examValue = s.nextLine();
}
else if (s.hasNextInt())
{
score = s.nextInt();
}
}
arrayList = {firstName, lastName, ID, examValue, score};
return arrayList;
}
首先,你不能初始化一个数组作为Exam[] arrayList = null;
,然后重新分配给长度为5
的阵列值其次,您的ArrayList
是不同的对象和原语(String
,int
)的列表,并且与指定的类型Exam[]
不匹配。
要么更改分配给Exam
列表的对象的类型,要么确保列表中的所有对象都是Exam
类型。
您可以尝试使用arrayList = new Exam[]{ /* stuff */ }
。您尝试使用的语法仅在数组声明中有效。
此外,您不能使用不同基本类型的变量初始化Exam
类型的数组。
我是新来的对象,你能否提供任何使用数组中的对象@ Mints97的例子? – jordan 2015-02-09 20:09:08
这里Exam[] arrayList = null;
你说的阵列的类型是考试,那么你说 arrayList = {firstName, lastName, ID, examValue, score};
阵列的类型为String是2所陈述相互矛盾
你不能初始化数组声明后的方式。请参阅http://stackoverflow.com/questions/5387643/array-initialization-syntax-when-not-in-a-declaration – Mints97 2015-02-09 18:36:50