简体   繁体   English

Java switch 语句将变量从一种情况调用到另一种情况

[英]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.我正在制作一个非常简单的程序,它使用 switch 语句来选择要归因于学生的数据(案例 1 是学生姓名,案例 2 是 3 个考试成绩等)但是,当我想打印概述时,案例 3对于学生,案例无法调用在案例 1 中修改的 firstName 和 lastName 字符串,而是在我实例化字符串时打印出 aaa 和 bbb 。 This is a very simple question but how do I make it so that case 3 can read the updated variables from case 1.这是一个非常简单的问题,但我如何做到这一点,以便案例 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;
            }
        }
    } 
}

Try to declare your variables outside from the while loop, like:尝试在 while 循环之外声明您的变量,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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