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.