Консоль зависает при попытке распечатать все узлы цепочки по порядку - PullRequest
0 голосов
/ 10 ноября 2018

Я пытался разобраться с этой проблемой уже два дня, спросил нескольких моих одноклассников, и никто не смог найти проблему, любая помощь будет признательна, так как этот проект должен выйти завтра утром.

Итак, инструкции для кода должны состоять из трех классов: Книга - имеет имя и автора. Автор - имеет имя и цепочку узлов типа книги (список книг, составленный автором). Библиотека - имеет две цепочки узлов, одну из книг типа (содержит все библиотечные книги) и одну из автора типа (содержит всех авторов, у которых есть книги в библиотеке).

Тогда нам нужно построить это меню:

1 -- Add book to library
2 -- Print all books
3 -- Print all authors
4 -- Print books of author
5 -- Get Number of Book
6 -- Exit the program

А проблема с 2 - «напечатать все книги»

Чтобы напечатать все книги, я создал в библиотеке функцию с именем PrintBooks, которая по сути является toString () для цепочки узлов LibraryBooks:

public string PrintBooks()
    {
        string str = "";
        Node<Book> search = LibraryBooks;
        while (search != null)
        {
            str = str + search.GetInfo().GetName() + " " + search.GetInfo().GetAuthor() + " -> ";
            search = search.GetNext();
        }
        return str;
    }

И вот как я использую его в Main:

static void Main(string[] args)
    {
        int x = 0;
        Node<Book> LibraryBooks = new Node<Book>(null);
        Node<Author> LibraryAuthors = new Node<Author>(null);
        Library library = new Library(LibraryBooks, LibraryAuthors);
        Console.WriteLine("1 -- Add book to library");
        Console.WriteLine("2 -- Print all books");
        Console.WriteLine("3 -- Print all authors");
        Console.WriteLine("4 -- Print books of author");
        Console.WriteLine("5 -- Get Number of Book");
        Console.WriteLine("6 -- Exit the program");

        while (x != 6) //6 -- Exit the program
        {
            x = int.Parse(Console.ReadLine());
            if (x == 1) //1 -- Add book to librarybooks
            {
                string name=null, author=null;

                Console.WriteLine("Please Enter Your Book's Name");
                name = Console.ReadLine();

                Console.WriteLine("Please Enter Your Book's Author's Name");
                author = Console.ReadLine();

                Book book = new Book(name, author);
                library.AddBook(book);

                Console.WriteLine("1 -- Add book to library");
                Console.WriteLine("2 -- Print all books");
                Console.WriteLine("3 -- Print all authors");
                Console.WriteLine("4 -- Print books of author");
                Console.WriteLine("5 -- Get Number of Book");
                Console.WriteLine("6 -- Exit the program");

            }
            if (x == 2) //2 -- Print all books
            {
                string debug = ""; 
                debug = library.PrintBooks();
                Console.WriteLine(debug);

                Console.WriteLine("1 -- Add book to library");
                Console.WriteLine("2 -- Print all books");
                Console.WriteLine("3 -- Print all authors");
                Console.WriteLine("4 -- Print books of author"); 
                Console.WriteLine("5 -- Get Number of Book");
                Console.WriteLine("6 -- Exit the program");

            }

Кроме того, AddBook, который используется для добавления книги в LibraryBooks внутри библиотеки, является функцией в библиотеке:

public void AddBook(Book book)
    {
        if (LibraryBooks == null)
        {
            LibraryBooks.SetInfo(book);
            LibraryBooks.SetNext(null);
        }
        else
        {
            LibraryBooks.SetNext(LibraryBooks);
            LibraryBooks.SetInfo(book);
        }

Теперь, когда я пытаюсь использовать PrintBooks, возникает ошибка, консоль всегда зависает при выполнении этой строки:

debug = library.PrintBooks();

Таким образом, я подумал, что проблема была в PrintBooks, но мои одноклассники использовали его почти точно так же, и он работал для них, может быть, печатные книги на самом деле не используют те же самые библиотечные книги, как та, к которой были добавлены книги в AddBook? Как видите, этот код не слишком сложен, просто я новичок в нем, поэтому у меня возникают проблемы с отладкой ошибок, которые не выдают мне сообщение об ошибке.

Я буду более чем рад добавить в этот пост любую другую часть проекта, необходимую для решения этой проблемы.

Спасибо, что нашли время, чтобы прочитать это

Редактировать: полный код ниже, чтобы повторить ошибку, есть много временных частей, которые вы можете просто проигнорировать, части, которые я загрузил ниже, являются связанными

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloEran
{
class Node<T>
{
    private T info;
    private Node<T> next;
    public Node(T info)
    {
        this.info = info;
        this.next = null;
    }
    public Node(T info, Node<T> next)
    {
        this.info = info;
        this.next = next;
    }
    public T GetInfo()
    {
        return info;
    }
    public Node<T> GetNext()
    {
        return next;
    }
    public void SetInfo(T info)
    {
        this.info = info;
    }
    public void SetNext(Node<T> next)
    {
        this.next = next;
    }
    public int GetSize()
    {
        Node<T> pos = this;
        int count = 0;

        while (pos != null)
        {
            count++;
            pos = pos.GetNext();
        }
        return count;
    }

    public String ToString()
    {
        return this.info.ToString();
    }
}
class Program
{
    static void Main(string[] args)
    {
        int x = 0;
        int id = 1;
        Node<Book> LibraryBooks = new Node<Book>(null);
        Node<Author> LibraryAuthors = new Node<Author>(null);
        Library library = new Library(LibraryBooks, LibraryAuthors);
        Console.WriteLine("1 -- Add book to library");
        Console.WriteLine("2 -- Print all books");
        Console.WriteLine("3 -- Print all authors");
        Console.WriteLine("4 -- Print books of author");
        Console.WriteLine("5 -- Get Number of Book");
        Console.WriteLine("6 -- Exit the program");

        while (x != 6) //6 -- Exit the program
        {
            x = int.Parse(Console.ReadLine());
            if (x == 1) //1 -- Add book to library
            {
                string name=null, author=null;

                Console.WriteLine("Please Enter Your Book's Name");
                name = Console.ReadLine();

                Console.WriteLine("Please Enter Your Book's Author's Name");
                author = Console.ReadLine();

                Book book = new Book(name, author, id);

                library.AddBook(book);

                id++;
                Console.WriteLine("1 -- Add book to library");
                Console.WriteLine("2 -- Print all books");
                Console.WriteLine("3 -- Print all authors");
                Console.WriteLine("4 -- Print books of author");
                Console.WriteLine("5 -- Get Number of Book");
                Console.WriteLine("6 -- Exit the program");

            }
            if (x == 2) //2 -- Print all books
            {
                string debug = ""; 
                debug = library.PrintBooks();
                Console.WriteLine(debug);

                Console.WriteLine("1 -- Add book to library");
                Console.WriteLine("2 -- Print all books");
                Console.WriteLine("3 -- Print all authors");
                Console.WriteLine("4 -- Print books of author"); 
                Console.WriteLine("5 -- Get Number of Book");
                Console.WriteLine("6 -- Exit the program");

            }
            if (x == 3) //3-- Print all authors
            {

            }
            if (x == 4) //4-- Print books of author
            {

            }
            if (x == 5) //5-- Get Number of Book
            {
                string numname = null, numauthor = null;
                Console.WriteLine("Please Enter Your Book's Name");
                numname = Console.ReadLine();
                Console.WriteLine("Please Enter Your Book's Author's Name");
                numauthor = Console.ReadLine();

                library.Idbook(numname, numauthor);

            }
        }
    }
}
class Book
{
    private string author, name;
    private int id;

    public Book(string name, string author,int id)
    {
        this.name = name;
        this.author = author;
    }
    public string GetAuthor()
    {
        return author;
    }
    public string GetName()
    {
        return name;
    }
    public int Getid()
    {
        return id;
    }
    public void Setid(int id)
    {
        this.id = id;
    }
    public string ToString()
    {
        return "bookID : " + id + " , BookName : " + name + " Author'sName : " + author;
    }
}
class Author
{
    private string name;
    private Node<Book> books;

    public Author(string name, Node<Book> books)
    {
        this.name = name;
        this.books = books;
    }
    public Node<Book> GetBooks()
    {
        return books;
    }
    public string PrintAuthorsBooks()
    {
        string str = "";
        return str;
    }

}
class Library
{
    private Node<Book> LibraryBooks;
    private Node<Author> LibraryAuthors;

    public Library(Node<Book> LibraryBooks, Node<Author> LibraryAuthors)
    {
        this.LibraryBooks = LibraryBooks;
        this.LibraryAuthors = LibraryAuthors;
    }
    public Node<Book> GetLibraryBooks()
    {
        return LibraryBooks;
    }
    public Node<Author> GetLibraryAuthors()
    {
        return LibraryAuthors;
    }

    public void AddBook(Book book)
    {
        if (LibraryBooks == null)
        {
            LibraryBooks.SetInfo(book);
            LibraryBooks.SetNext(null);
        }
        else
        {
            LibraryBooks.SetNext(LibraryBooks);
            LibraryBooks.SetInfo(book);
        }
    }
    public void AddAuthor(Author author)
    {
        if (LibraryAuthors.GetInfo() == null)
        {
            LibraryAuthors.SetInfo(author);
            LibraryAuthors.SetNext(null);
        }
        else
        {
            LibraryAuthors.SetInfo(author);
            LibraryAuthors.SetNext(LibraryAuthors);
        }
    }
    public string PrintBooks()
    {
        string str = "";
        Node<Book> search = this.LibraryBooks;
        while (search.GetInfo() != null)
        {
            str = str + search.GetInfo().GetName() + " " + search.GetInfo().GetAuthor() + " -> ";
            search = search.GetNext();
        }
        return str;
    }
    public void Idbook(string name, string author)
    {

        Node<Book> temp = this.LibraryBooks;
        int l = temp.GetSize();
        bool exist = false;

        for (int i = 0; i < l; i++)
        {
            if (temp.GetInfo().GetName() == name && temp.GetInfo().GetAuthor() == author)
            {
                exist = true;
                Console.WriteLine("The ID of this book is " + temp.GetInfo().Getid());
            }
            temp = temp.GetNext();
        }

        if (exist == false)
            Console.WriteLine("This book does not exist in the library");

    }
    }
}
...