我正在制作一个非常简单的程序,该程序使用switch语句选择要归给学生的数据(第一种情况是学生姓名,第二种情况是3个考试成绩等),但是,在第3种情况下,我想打印概览对于该学生,该案例无法调用在案例1中修改的firstName和lastName字符串,而是当我实例化字符串时它们打印出aaa和bbb。这是一个非常简单的问题,但是我该如何做,以便案例3可以从案例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;
            }
        }
    }
}

最佳答案

尝试在while循环之外声明变量,例如:

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

10-06 14:59