-1

我正在使用 Java S2SE 制作一个简单的原型项目。目标是制作一个文本文件,逐行读取,填充链接列表,然后要求用户输入名字和名字。

文本文件格式为:

名字 名字 名字 移动 家 mobile2 办公室

contact1contact2 手机之家 mobile2s 办公室

我连接文本文件中的名字和第二个名字。

然后我要求用户输入名字和名字,并使用这两个字符串的连接,将搜索填充的链接列表。无论出现包含具有这些名字和第二个名称的字符串的节点,拆分该节点并显示该节点的结果

我的代码是:

try {
    String fullname;
    String mobile;
    String home;
    String mobile2;
    String office;

    Node current=first;

    while(current.data == null ? key !=null : !current.data.equals(key)) {
        String splitter[]=current.next.data.split(" ");

        //fullname=splitter[9];
        mobile=splitter[1];
        home=splitter[2];
        mobile2=splitter[3];
        office=splitter[4];

        if(current.next.data.split(" ")==null?key==null:){

            mobilefield.setText(mobile);
            homefield.setText(home);
            mobilefield2.setText(mobile2);
            officefield.setText(office);
        } else {
            throw new FileNotFoundException("SORRY RECORD NOT LISTED IN DATABASE");
        }
            break;
    }
} catch(Exception e) {
        JOptionPane.showMessageDialog(this,e.getMessage()
        +"\nPLEASE TRY AGAIN !","Search Error", JOptionPane.ERROR_MESSAGE);
}

问题是一切都很好,但是对于列表中的第一个和直到第 n-1 个节点的搜索出错,但在此搜索中没有到达最后一个节点。

4

2 回答 2

0

快速浏览一下,您正在尝试引用一个next可能为空的节点。

current.next.data可能是null,如果是这样,那么您将获得 NPE。

你的循环应该专注于它正在处理的第 i 个部分 - 也就是说,一个大小为n的链表,当我得到一个n的节点i时,我应该这样

此外,您不应该在其中没有数据的节点中工作。跳过那些空的。

while(current.data != null)

最后,提前你的current参考,否则你会无限期地循环。

current = current.next;

另一项观察:

  • 编辑时,我从上下文中不知道这两行是否应该在同一行。如果是这种情况,那么您可能希望使用常量代替原始整数来指示去哪里 - 例如,您要查找的名称将在[0]其中并且可以称为FULL_NAME.
于 2012-12-26T19:26:13.890 回答
0

根据我从您的问题中收集到的信息,我已经修改了您的代码。这应该有希望工作:

try {
String fullname;
String mobile;
String home;
String mobile2;
String office;

Node current;

    //This loop will start from the first `Node`, check for `null`, then check if it is equal to the `key`. If not, then it will advance to `next`
for(current=first; current!=null && !current.data.equals(key); current = current.next);

    //the loop will terminate if current is null or is equal to key. If it is equal to key, we should display data.
if(current.data.equals(key))
{

    String splitter[]= current.data.split(" ");

    fullname=splitter[0];
    mobile=splitter[1];
    home=splitter[2];
    mobile2=splitter[3];
    office=splitter[4]; 

    mobilefield.setText(mobile);
    homefield.setText(home);
    mobilefield2.setText(mobile2);
    officefield.setText(office);
}
else
    throw new FileNotFoundException("SORRY RECORD NOT LISTED IN DATABASE");

} catch(Exception e) {
    JOptionPane.showMessageDialog(this,e.getMessage()
    +"\nPLEASE TRY AGAIN !","Search Error", JOptionPane.ERROR_MESSAGE);

编辑:添加评论。

于 2012-12-26T19:29:15.953 回答