1

I am trying to create an interactive menu for my program which deals with arrays of objects ("Students"). The problem is in my second switch function, case 1. It keeps giving me an error that myArray has not been initialized. I declared myArray first in my main method, and thought that initializing it in my first switch would initialize all cases of myArray. (Note, my first switch with case "Yes" and case "No" works without issues.) To me it appears that I cannot access the initialized array outside of the while loop. Is there a way around this?

public static void main(String[] args) {

    Student[] myArray;

    System.out.println("Welcome.");
        //stuff
        System.out.println("Please type \"Yes\" or \"No\".");
        switch (keyboard.next()) {

        case "Yes":
            String filename = myFile;
            myArray = readListFromFile(filename); //sends to setters in class Student
            //more stuff
            break;

        case "No":
            myArray = readList(); //allows for manual input then sends to setters
            //stuff
            break;

        default:
            System.out.println("Unrecognized option.");

        }

    // add a new switch 
    switch(keyboard.nextInt()) {

        case 1:
            averageScore(myArray); //The local variable myArray may not have been initialized

        }
    }

Thanks in advance.

kezchino
  • 11
  • 3
  • 1
    It says this because it might be possible that your while loop never gets executed. hence add a default initialization. – CoderNeji Sep 28 '15 at 11:36
  • add a default initialization before the while loop. – Stultuske Sep 28 '15 at 11:36
  • The compiler needs to know that your variable gets initialised before you read it. Every path of execution needs to initialise the variable. The easiest way to ensure this is to assign it something when it is declared. – khelwood Sep 28 '15 at 11:39
  • possible duplicate of [Declaring variables inside or outside of a loop](http://stackoverflow.com/questions/8803674/declaring-variables-inside-or-outside-of-a-loop) – Stefan Dollase Sep 28 '15 at 11:46

2 Answers2

1

There are two options. Either declare your array at the beginning:

Student[] myArray = null;

or in the switch statement, in the default case:

myArray = null;

Or init as an empty array to avoid Nullpointer.

Thomas R.
  • 7,988
  • 3
  • 30
  • 39
0

If Input is not "Yes" or "No" you will go through default only. Your array isn't initialized then.

Student[] myArray = null;

at declaration or

myArray = null

in the default part of your switch will fix this issue.

Meinus
  • 16
  • 2