重点是编写一个程序,通过搜索他们的ID号来查找员工,并打印出所有员工的所有信息,并打印出单个员工的信息。我需要帮助(搜索),如果单独打印一个员工是正确的吗?谢谢!
班级员工代码:
public class Employee {
private String name;
private int id;
private int salary;
private boolean bonus;
public Employee(String n, int i, int s, boolean b) {
name = n;
id = i;
salary = s;
bonus = b;
}
public void computeSalary(int s, boolean b) {
if (b == true)
salary += 2000;
}
public void printInfo() {
System.out.print("Name: "+name+" ID: "+id+" Salary: "+salary+" Bonus: "+bonus+" ");
}
类EmployeeApp类代码:
import java.util.Scanner;
public class EmployeeApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the name: ");
String n = in.nextLine();
System.out.print("Enter the ID: ");
int g = in.nextInt();
System.out.print("Enter the salary: ");
int s = in.nextInt(); in.nextLine();
System.out.print("true or false for bonus? ");
boolean b = in.nextBoolean();
Employee e = new Employee(n, g, s, b);
e.computeSalary(s, b);
e.printInfo();
}
}
public class Company{
private Employee[] e = new Employee[4];
public void printAllEmployees() {
for(int i = 0; i < e.length; i++)
e[i].printInfo();
}
public Employee searchEmployee(int i) {
Employee temp = null;
for (int j = 0; j < e.length; j++) {
if (Employee.id == i)
temp = Employee;
}
return temp;
}
public void printAnEmployee(Employee e) {
e.printInfo();
}
}
答案 0 :(得分:0)
将员工置于一个能够简单搜索后者的结构中,如下所示:
private Map<Integer, Employee> e = new HashMap<Integer, Employee>();
public void printAllEmployees() {
for( Integer key : e.keySet() )
System.out.println(e.get( key ));
}
public Employee searchEmployee(int i) {
return e.get(i);
}
答案 1 :(得分:0)
我不知道您提供给我们的代码是如何为用户工作的,因为您的课程中存在一些小问题。 首先,在Employee中使用setter和getter是一个好习惯,因为安全性很好地封装了一个对象,所以如何构造它们plz参考本教程 http://www.tutorialspoint.com/java/java_encapsulation.htm
其次,在您的EmployeeApp类中 当你问这个时
System.out.print("true or false for bonus? ");
boolean b = in.nextBoolean();
不清楚用户必须输入什么类型的输入,因此最好将第一行更改为
System.out.print("true or false for bonus? \nplease enter true or false");
第三,将公司类放在不同的文件中是好的,在公司类中有一些小问题如下
注意:Employee是一个类,e是一个Employee类型
的数组public Employee searchEmployee(int i) {
Employee temp = null;
for (int j = 0; j < e.length; j++) {
if (**Employee.id** == i)
**temp = Employee;**
}
return temp;
}
更改为
public Employee searchEmployee(int i) {
Employee temp = null;
for (int j = 0; j < e.length; j++) {
if (e[i].getId() == i) {
temp = e[i];
}
}
return temp;
}
最后,如果您需要添加更多员工,则需要将其置于while循环中。因此,虽然循环将是正常的,例如用户按下X。