whats the right way to put a method(with array code) in a switch statement?
public static void prtEmployees(String empNo[], String Name[], int rate[]) {
System.out.println("Employee No. Employee Name Rate/Hour");
for(int i = 0; i < empNo.length; i ) {
System.out.printf("%s: %s", empNo[i], Name[i], rate[i]);
}
}
private void Action(int choice) {
switch(choice) {
case 1:
prtEmployees(); // im having an error here
break;
CodePudding user response:
The problem in your code is not about using a switch, but calling a method with a wrong amount of parameters. The method prtEmployees requires 3 parameters:
- String array of employee no's
- String array of employee names
- Int array of employee rates
The 3 parameters are always required to be placed.
Based on your code snippet, I can't see where your input is, where your employee data is coming from. But I created a sample where I call your method in a main class with some dummy data to give an example:
public class Main {
public static void main(String[] args) {
String[] employeeNos = {"1", "2", "3"};
String[] names = {"Alfred", "James", "Siegfried"};
int[] rates = {2,3,5};
Action(1, employeeNos, names, rates);
Action(2, employeeNos, names, rates);
}
public static void prtEmployees(String[] employeeNumbers, String[] names, int[] rates) {
System.out.print("Employee No.\tEmployee Name\tRate/Hour\n");
for(int i = 0; i < employeeNumbers.length; i ) {
System.out.printf("%s.\t%s\t%d\n", employeeNumbers[i], names[i], rates[i]);
}
}
private static void Action(int choice, String[] employeeNos, String[] names, int[] rates) {
switch (choice) {
case 1:
prtEmployees(employeeNos, names, rates);
break;
case 2:
System.out.println("No employee print because of choice 1");
break;
default:
throw new IllegalArgumentException("Only choice 1 and 2 are allowed");
}
}
}
This gives as output:
Employee No. Employee Name Rate/Hour
- Alfred 2
- James 3
- Siegfried 5 Only choice 1 and 2 are allowed
Explanation First I call the action method with choice 1 and some dummy data, which will pass the dummy data to the print method and it will print out the 3 columns of employee data. Then I call the same method with choice value 2, which prints an additional single line, just to illustrate the functionality of it. Just for fun I added a default behaviour that other values than 1 and 2 will throw an exception.