gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:52:34 25 4
gpt4 key购买 nike

我正在制作一个非常简单的程序,它使用 switch 语句来选择将哪些数据归因于学生(情况 1 用于学生姓名,情况 2 用于 3 个测试分数等)但是,当在情况 3 中时,当我想要打印学生的概述,该案例无法调用案例 1 中修改的名字和姓氏字符串,而是在我实例化字符串时打印出 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...
}

关于Java switch 语句将变量从一种情况调用到另一种情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53644430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com