【发布时间】:2021-11-29 08:47:39
【问题描述】:
我正在处理我的类的最终项目,我们正在创建一个类来存储员工、ID# 和工资范围,然后创建添加到类中的方法和数组。到目前为止,我已经将它设置为添加新员工并打印所有员工,但我有点困惑如何获得这两个提示:
- 检索特定员工的数据 - 提示用户输入员工 ID 并显示相应的员工数据:ID、姓名和薪水
- 根据范围检索具有工资的员工 - 提示用户输入最低和最高工资,并显示所有工资在该范围内的员工。在单独的行上显示每个员工的所有信息 - 姓名、ID 和薪水
如何将其合并到以下代码中?
import java.util.ArrayList;
import java.util.Scanner;
public class FP {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<EmployeeData> companyData = new ArrayList<>();
// Boolean loop and while loop to restart the program in all cases but 3
boolean loopAgain = true;
while (loopAgain) {
System.out.println("Main Menu:");
System.out.println("1: Load New Employee Data");
System.out.println("2: Print Employee Data");
System.out.println("3: Exit");
int answer = in.nextInt();
switch (answer) {
// Case 1 to be called on when user selects "1"
case 1: {
System.out.println("Load New Employee Data:");
System.out.println("Please enter the number of new Employees to be added to
the sytem.");
System.out.println();
int loop = in.nextInt();
//For loop to add the number to class EmployeeData
for (int i =0; i < loop; i++) {
companyData.add(new EmployeeData());
}
} break;
// Case 2 to be called on when user selects "2"
case 2: {
// for loop to display the employees information after being entered by the user
for (EmployeeData x : companyData) {
x.printData();
}
} break;
// Case 2 to be called on when user selects "3" breaking the loop and ending the program
case 3: loopAgain = false; break;
}
}
}
}
// Class to store information for user input of employee data
class EmployeeData {
// String variable for names
String name;
// Int variables for ID and Salary
int id, salary;
public EmployeeData() {
// scan options and prompts for user input to be stored in class Employee Data
Scanner in = new Scanner(System.in);
System.out.println();
System.out.println("Enter Employee Name: ");
System.out.println();
String name = in.nextLine();
System.out.println();
System.out.println("Enter Employee ID:");
System.out.println();
int id = in.nextInt();
System.out.println();
System.out.println("Enter Employee Salary: ");
System.out.println();
int salary = in.nextInt();
// callable and modified variables stored for case 2
this.name = name;
this.id = id;
this.salary = salary;
}
// print section to be shown to user when case 2 is selected
public void printData() {
System.out.println();
System.out.println("Employee: " + this.name);
System.out.println();
System.out.println("ID: " + this.id);
System.out.println();
System.out.println("Salary: " + this.salary);
System.out.println();
}
}
【问题讨论】:
-
欢迎来到 StackOverflow。请不要分享您的整个项目并要求我们为您完成它。真诚地尝试自己解决问题。如果您遇到困难,请仅共享代码的相关部分。 meta.stackoverflow.com/questions/334822/…stackoverflow.com/help/minimal-reproducible-example