员工类:
public class Employee
{
String ID;
String Fname;
String Lname;
String City;
String Major;
int GPA;
public Employee()
{
GPA = 0;
}
public void ShowInfo()
{
JOptionPane.showMessageDialog(null, "ID: " + ID + "\nFirst Name: " + Fname + "\nLast Name:" + Lname + "\nCity: " + City + "\nMajor: " + Major + "\nGPA: " + GPA);
}
public void EnterInfo()
{
ID = JOptionPane.showInputDialog("Enter Student ID");
Fname = JOptionPane.showInputDialog("Enter Student First Name");
Lname = JOptionPane.showInputDialog("Enter Student Last Name");
City = JOptionPane.showInputDialog("Enter Student City");
Major = JOptionPane.showInputDialog("Enter Student Major");
String gpa = JOptionPane.showInputDialog("Enter Student GPA");
GPA = Integer.parseInt(gpa);
}
}
}
链接列表:
public class EmployeeList
{
Node first;
Node last;
int count;
public EmployeeList()
{
first = new Node();
first = null;
last = new Node();
last = null;
count = 0;
}
public boolean empty()
{
return first == null;
}
public void add(Employee emp)
{
Node newEmployee = new Node();
newEmployee.e = emp;
newEmployee.e.EnterInfo();
newEmployee.next=null;
if(empty())
{
first=newEmployee;
last=first;
}
else
{
last.next = newEmployee;
last = last.next;
}
count++;
}
public boolean search(String id)
{
Node temp = new Node();
Employee emp = new Employee();
temp = first;
while(temp!=null)
{
emp = temp.e;
if(id.equals(emp.ID))
{
emp.ShowInfo();
return true;
}
temp=temp.next;
}
return false;
}
public boolean delete(String id)
{
Employee emp = new Employee();
if(!empty())
{
if(first.e.ID.equals(id))
{
first=first.next;
return true;
}
else
{
Node previous = new Node();
Node temp = new Node();
previous = first;
temp = first.next;
while(temp!=null)
{
emp = temp.e;
if(id.equals(emp.ID))
{
count--;
previous.next = temp.next;
return true;
}
previous = previous.next;
temp = temp.next;
}
return false;
}
}
return false;
}
public String ALL()
{
String all = new String();
Node temp = new Node();
Employee emp = new Employee();
temp = first;
while(temp!=null)
{
emp = temp.e;
all = all + emp.ID + "-";
temp = temp.next;
}
all = all + "null";
return all;
}
}
我真的不知道这里有什么问题,如果我尝试打印它们,我会不断获得最后输入的值。
节点类:
public class Node
{
Employee e = new Employee();
Node next;
}
通过搜索我没有得到任何结果,只找不到员工ID。 EnterInfo方法仅用于输入变量(ID,Fname .....)
有任何帮助吗?并谢谢。
编辑:我知道错误的方式,我应该添加getter和setter,但这就是老师的开始,并告诉我们这样开始。
答案 0 :(得分:2)
您的搜索失败,因为您错误地测试了字符串相等性。这一行:
if(emp.ID == id)
测试对象引用相等性。它仅适用于实习值(超出了您的分配范围)。你也应该改变它:
if(id.equals(emp.ID))
关于代码的一些快速说明:
在您的搜索方法的开头,您将不必要地创建 节点实例
节点temp = new Node();
您在delete
中错误地测试字符串相等性
方法