-1

why is here: arrayList = {firstName, lastName, ID, examValue, score}; gives an error?? The method should call a constructor which is Exam(String firstName, String lastName, int ID, String examType, int score), so what's is wrong with this method? Thanks in advance!

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;


    }
jordan
  • 29
  • 2
  • 7
  • 1
    You can't initialize an array that way after the declaration. See http://stackoverflow.com/questions/5387643/array-initialization-syntax-when-not-in-a-declaration –  Feb 09 '15 at 18:36

3 Answers3

0

Firstly, you cannot initialize an array as Exam[] arrayList = null; and then reassign the value to an array of length 5.

Secondly, your ArrayList is a List of different objects and primitives (String, int), and does not match the specified type Exam[].

Either change the type of objects assigned to the Exam list, or make sure all of the objects in the list are of type Exam.

rageandqq
  • 2,221
  • 18
  • 24
  • how can all of the objects be of type Exam? Could please provide any examples of all of the objects of type Exam? @rageandqq – jordan Feb 09 '15 at 20:05
  • You would have to make sure all of the objects in the list (`firstName, lastName, ID, examValue, score`) are of type Exam and not what they currently are (string, int, etc). That, or change `arrayList` to accept different types (have it just as an ArrayList` type and not an array of `Exam` objects). – rageandqq Feb 09 '15 at 20:22
0

You can try using arrayList = new Exam[]{ /* stuff */ }. The syntaxis you tried to use is valid only in an array declaration.

Also, you can't initialize an array of type Exam with variables of different basic types.

  • I'm new to objects, Could you please provide any examples using objects in an array @Mints97 ? – jordan Feb 09 '15 at 20:09
0

Here Exam[] arrayList = null; you say array is of type Exam then you say arrayList = {firstName, lastName, ID, examValue, score}; array is of type String that 2 statements contradict each other

singhakash
  • 7,891
  • 6
  • 31
  • 65