簡體   English   中英

打印出鏈表的一部分

[英]Printing out a section of a linked list

所以我有這個充滿名字的鏈表。 用戶將搜索名稱的第一個字母,並打印出名稱以字母開頭的節點。 我跑的時候以為我沒有收到任何回復。 如果我在循環中插入一些打印線,我會回來的。

這里是:

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();
    }
}

你在這里遇到了無限循環。

您只需要一個while循環,無論元素是否以搜索到的字母開頭,您都必須跳轉到列表中的下一個元素。

所以重寫你的if語句並刪除第二個while循環。 還要確保始終轉到下一個元素。

編輯:仔細看看你的代碼,我意識到你也沒有檢查你從用戶那里得到的輸入。 他實際上不限於單個字符,但可以輸入整行文本。 因此,要么修復您給出的解釋,要么引入輸入驗證(如果輸入無效,則包括一些錯誤消息)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM