为什么数组给出错误?

问题描述:

为什么在这里: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; 


    } 
+1

你不能初始化数组声明后的方式。请参阅http://*.com/questions/5387643/array-initialization-syntax-when-not-in-a-declaration – Mints97 2015-02-09 18:36:50

首先,你不能初始化一个数组作为Exam[] arrayList = null;,然后重新分配给长度为5

的阵列值其次,您的ArrayList是不同的对象和原语(Stringint)的列表,并且与指定的类型Exam[]不匹配。

要么更改分配给Exam列表的对象的类型,要么确保列表中的所有对象都是Exam类型。

+0

所有对象如何能成为Exam类型的?请提供所有类型考试对象的例子吗? @rageandqq – jordan 2015-02-09 20:05:02

+0

您必须确保列表中的所有对象('firstName,lastName,ID,examValue,score')属于Exam类型,而不是它们目前的内容(string,int等)。也就是说,或者改变'arrayList'来接受不同的类型(把它作为一个ArrayList类型,而不是一个'Exam'对象的数组)。 – rageandqq 2015-02-09 20:22:54

您可以尝试使用arrayList = new Exam[]{ /* stuff */ }。您尝试使用的语法仅在数组声明中有效。

此外,您不能使用不同基本类型的变量初始化Exam类型的数组。

+0

我是新来的对象,你能否提供任何使用数组中的对象@ Mints97的例子? – jordan 2015-02-09 20:09:08

这里Exam[] arrayList = null;你说的阵列的类型是考试,那么你说 arrayList = {firstName, lastName, ID, examValue, score};阵列的类型为String是2所陈述相互矛盾