我正在制作一个非常简单的程序,该程序使用switch语句来选择要归因于学生的数据(案例1代表学生姓名,案例2代表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;
}
}
}
}
答案 0 :(得分:1)
尝试在while循环之外声明变量,例如:
String firstName = "aaa";
String lastName = "bbb";
while (response < 5) {
//All code here...
}