I’m making a program that has menus and I’m using switch to navigate between the menus.
I have something like this:
switch (pick) {
case 1:
// Here the program ask the user to input some data related with students (lets say
// name and dob). Student is a class and the students data is stored in 1 array of
// students. If I do:
// for (Student item: students){
// if (item != null){
// System.out.println(item);
// }
// }
// It will print the name and dob of all the students inserted because I've created
// a toString() method that returns the name and dob of the students
case 2:
// On case 2 at some point I will need to print the array created on the case
// above. If I do again:
// for (Student item: students){
// if (item != null){
// System.out.println(item);
// }
// }
// It says that students variable might have not been initialized.
Question:
If a variable is created in one case it’s values can’t be used in another case?
What I was trying to do was first enter in case 1 and input the values and then, in case 2 be able to use some of the values defined in case 1.
If this can’t be done, please point me in the right direction.
Please keep in mind that I’ve started to learn java only a few weeks.
favolas
Declare the variables before the switch and you’ll be able to use them in all cases