打印出链表的一部分

时间:2013-11-07 08:06:56

标签: java search linked-list nodes

所以我有这个充满名字的链表。用户将搜索名称的第一个字母,并打印出名称以字母开头的节点。我跑的时候以为我没有收到任何回复。如果我在循环中插入一些打印线,我会回来的。

这是:

public String printSection(){
        LinkedListNode current = front;
        String searchedLetter;
        int i = 0;
        String retSec = "The nodes in the list are:\n";

        //Get the input of the name being removed
        Scanner s = new Scanner(System.in);
        System.out.println("Enter the first letter of the section you would like to print out");
        searchedLetter = s.nextLine();

        //while current is not null
        while(current != null){
            //if the data in current starts with the letter entered for searchedLetter
            if(current.getData().startsWith(searchedLetter)){
            //if(current.getData().substring(0,1) == searchedLetter){
                        //Increment the number of the node
                        i++;
                        //Print the node(s)
                        retSec += "Node " + i + " is: " + current.getData() + "\n";
                        //Traverse the list
                        current = current.getNext();
                        System.out.println("You made it here");
            }
        }
        return retSec;
    }
}

这是:(新的工作方法)

public void printSection(){

    LinkedListNode current = front;
    String searchedLetter;
    int i = 0;

    //Get the input of the name being removed
    Scanner s = new Scanner(System.in);
    System.out.println("Enter the first letter of the section you would like to print out");
    searchedLetter = s.nextLine();

    //while current is not null
    while(current != null){
        //if the data in current starts with the letter entered for searchedLetter
        if(current.getData().startsWith(searchedLetter)){
                    //Increment the number of the node
                    i++;
                    //Print the node
                    System.out.println("Node " + i + " is: " + current.getData());
        }
        //Traverse the list
        current = current.getNext();
    }
}

1 个答案:

答案 0 :(得分:2)

你在这里遇到了无限循环。

你只需要一个while循环,你必须跳转到列表中的下一个元素,无论元素是否以搜索到的字母开头。

重新编写if语句并删除第二个while循环。另外,请务必始终转到下一个元素。

编辑:深入了解您的代码我意识到您也没有检查用户提出的输入。他实际上不限于单个字符,但可以输入整行文本。所以要么修复你给他的解释,要么引入你的输入验证(如果输入无效,包括一些错误信息)。