gpt4 book ai didi

java - Switch Statement输出数据到新的Var中

转载 作者:行者123 更新时间:2023-12-02 05:26:35 27 4
gpt4 key购买 nike

我想知道如何将 switch 语句的结果放入新变量中。

这是我的代码,一旦 switch 语句找到正确的员工,我希望将此信息转到新变量。我该怎么做?

此外,如果我在“员工编号”字段中输入字符或字符串,如何让它返回并出错而不是导致应用程序崩溃?

package payRoll; // package Name

///////////////////////////////

import java.util.ArrayList;
import java.util.Scanner;

//////////////////// API Imports

public class Main {

public static void main(String[] args) {
Scanner keyboard = new Scanner ( System.in );

/////////// Code

String cacheEm = new String();

ArrayList<String[]> addresses = new ArrayList<String[]>();

String[] EmNo = new String[4]; {
EmNo[0] = "Shaun Clark";
EmNo[1] = "Ann Clark";
EmNo[2] = "Darren Watters";
EmNo[3] = "Daniel Brightman";

addresses.add(EmNo);

}
boolean repeat;
do {
repeat = false;

System.out.print("Please Enter Employee number: ");
int employeeNum = keyboard.nextInt();
switch (employeeNum)
{
case 1: employeeNum = 0;
System.out.println("Employee Indexed as " + EmNo[0]);
break;
case 2: employeeNum = 1;
System.out.println("Employee Indexed as " + EmNo[1]);
break;
case 3: employeeNum = 2;
System.out.println("Employee Indexed as " + EmNo[2]);
break;
case 4: employeeNum = 3;
System.out.println("Employee Indexed as " + EmNo[3]);
break;
default:
System.err.println("\n Employee Not found!! \n");
repeat = true;
}
}
while(repeat);

keyboard.close();



////// output from switch needs to go into new variable for next function


}// end class
}// end main

最佳答案

您已经在 employeeNum 中得到了结果,只需检查它是否小于 4 就可以了。只需获取您应该执行的 EmNo[employeeNum] 而不是 switch 语句...

为了捕获输入中的错误,您应该使用 try-catch 语句捕获抛出的异常。

关于java - Switch Statement输出数据到新的Var中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25954473/

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