简体   繁体   中英

Java switch statements calling variables from one case to another

I am making a very simple program which uses switch statements to select which data to attribute to a student (case 1 is for student name, case 2 is for 3 test scores etc) However, when in case 3 when I want to print an overview of the student, the case is unable to call the firstName and lastName strings which were modified in case 1, instead they print out aaa and bbb when I instantiated the strings. This is a very simple question but how do I make it so that case 3 can read the updated variables from case 1.

import java.util.*;

public class studentDatabase { 
    public static void main (String [] args){

        int response = 0;
        Scanner input = new Scanner(System.in);
        while (response < 5) {
            //menu();
            System.out.print("\nEnter your selection: (1-5): ");
            response = input.nextInt();
            System.out.println();
            String firstName = "aaa";
            String lastName = "bbb";
            int[] scores = new int[3];

            switch(response) {
                case 1:
                    input.nextLine();
                    System.out.println("Enter first name and then last name");
                    firstName = input.nextLine();
                    lastName = input.nextLine();
                    break;

                case 2:

                    for (int i = 0; i < scores.length; i++){
                        System.out.println("Enter test # " + (i + 1));
                        scores[i] = input.nextInt();
                    }

                    break;

                case 3:
                    System.out.println(firstName + lastName);
                    System.out.println(scores[0] + "\n" + scores[1] + "\n" + scores[2]);
                    System.out.println((scores[0] + scores[1] + scores[2]) / 3);

                    break;
            }
        }
    } 
}

Try to declare your variables outside from the while loop, like:

String firstName = "aaa";
String lastName = "bbb";
while (response < 5) {
    //All code here...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM