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.

4
  • 1
    It says this because it might be possible that your while loop never gets executed. hence add a default initialization. Commented Sep 28, 2015 at 11:36
  • add a default initialization before the while loop. Commented Sep 28, 2015 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. Commented Sep 28, 2015 at 11:39
  • possible duplicate of Declaring variables inside or outside of a loop Commented Sep 28, 2015 at 11:46

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I worked out I could also use Student[] myArray = {};
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.