我想知道如何将switch语句的结果转换为新变量。
这是我的代码,一旦switch语句找到正确的员工,我希望此信息进入新变量。我该怎么办?
另外,如果我在Employee number字段中键入Char或String,我如何使它返回并出错而不是使应用程序崩溃?
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语句引发的异常。