我一直在构造一个带有一些参数(名称,id等)的新员工。我用一个简单的if / else在部门验证和名称编码中编写代码。由于某些原因,即使满足条件,它也总是会引发错误。我是Java的新手,我希望获得一些帮助。谢谢!
public class Employee {
int empId;
String empName;
String empDesig;
String empDept;
public void setEmpName(String name) {
if (name == null) {
System.out.println("Name cannot be null. Close app and try
again.");
System.exit(1);;
}
}
public void setEmptDesig(String desig) {
if(desig == "Developer" || desig == "Tester" || desig == "Lead" ||
desig == "Manager") {
return;
} else {
System.out.println("Designation is invalid. Close app and try
again.");
System.exit(1);
}
}
public void setEmptDept(String dept) {
if(dept == "TTH" || dept == "RCM" || dept == "Digital" || dept ==
"DevOps") {
return;
} else {
System.out.println("Department is invalid. Close app and try again.");
System.exit(1);
}
}
public Employee(int id,String name,String desig, String dept ) {
setEmpName(name);
setEmptDesig(desig);
setEmptDept(dept);
empId= id;
empName = name;
empDesig = desig;
empDept = dept;
}
}
public class CreateEmployee {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter ID");
String id = scan.nextLine();
int idInt = Integer.parseInt(id);
System.out.println("Enter Name");
String name = scan.nextLine();
System.out.println("Enter Designation");
String desig = scan.nextLine();
System.out.println("Enter Department");
String dept = scan.nextLine();
Employee emp = new Employee(idInt,name,desig,dept);
System.out.println(emp.empId +" "+ emp.empName + " " + emp.empDesig +
" " + emp.empDept);
}
}
即使假定符合条件,也会始终触发错误。