Повторная печать одной и той же части узла, помощь в создании кода на C # - PullRequest
0 голосов
/ 05 ноября 2018

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

Дело в том, что я создал класс для списка книг, который будет храниться в формате node<T>, но после того, как я собрал функцию добавления книги в список, я сделал это неправильно в функции «printchain», которая должна печатать все книги, заставляет многократно печатать одну и ту же «книгу» снова и снова.

Почему неправильно печатается node<T> книг? Пожалуйста, обратитесь в основном к классу "библиотечные книги" и к классу Main, так как именно здесь я имею дело с этой проблемой.

namespace ConsoleApp7
{

    public class book
    {
        private int id;
        private string authorname;
        private string name;

        public book(int id, string authorname, string name)
        {
            this.id = id;
            this.name = name;
            this.authorname = authorname;
        }


        public string getname()
        {
            return this.name;
        }
        public string getauthor()
        {
            return this.authorname;
        }
        public void setname(string name)
        {
            this.name = name;
        }
        public void setauthor(string authorname)
        {
            this.authorname = authorname;
        }
        public int getid()
        {
            return this.id;
        }
        public void setid(int id)
        {
            this.id = id;
        }
    }

    public class author
    {

        private string name;
        private librarybooks autbooks;

        public author(string name, librarybooks autbooks)
        {
            this.name = name;
            this.autbooks = autbooks;
        }
        public string getname()
        {
            return this.name;
        }
        public void setname(string name)
        {
            this.name = name;
        }

        public librarybooks getauthorsbooks()
        {
            return this.autbooks;
        }
        public void setauthorsbooks(librarybooks autbooks)
        {
            this.autbooks = autbooks;
        }

    }
    public class librarybooks
    {
        private node<book> books;

        public librarybooks()
        {
            this.books = null;
        }

        public node <book> Getbooks() { return books; }

        public void add(book book)
        {

            this.books = new node <book>(book, this.books);

        }

        public void printchain()
        {
            while (this.books.getNext().getValue() != null)
            {
                node<book> search = this.books;
                Console.WriteLine(search.getValue().getauthor() + " " + search.getValue().getid() + " " + search.getValue().getname());
                search = new node<book>(this.books.getNext().getValue(), this.books) ;
            }
        }
    }

    public class libraryauthors
    {
        private node<author> authors;

        public libraryauthors()
        {
            this.authors = null;
        }

        public void add(author author)
        {

            if (this.authors.getValue() == null)
            {
                this.authors.setValue(author);
                this.authors.setNext(null);
            }
            if (this.authors.getValue() != null)
            {
                this.authors.setNext(this.authors);
                this.authors.setValue(author);
            }

        }

    }

    public class node<T>
    {
        T value;
        node<T> next;

        public node(T x)
        {
            this.value = x;
            this.next = null;
        }
        public node(T x, node<T> next)
        {
            this.value = x;
            this.next = next;
        }
        public T getValue()
        {
            return this.value;
        }
        public void setValue(T value)
        {
            this.value = value;
        }
        public node<T> getNext()
        {
            return this.next;
        }
        public void setNext(node<T> next)
        {
            this.next = next;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            librarybooks ezer = new librarybooks();
            string str1, str2;
            int num1;
            Console.WriteLine("enter author");
            str1 = Console.ReadLine();
            Console.WriteLine("enter name");
            str2 = Console.ReadLine();
            Console.WriteLine("enter id");
            num1 = int.Parse(Console.ReadLine());
            book ezra=new book(num1,str2,str1);
            string str3, str4;
            int num2;
            Console.WriteLine("enter author");
            str3 = Console.ReadLine();
            Console.WriteLine("enter name");
            str4 = Console.ReadLine();
            Console.WriteLine("enter id");
            num2 = int.Parse(Console.ReadLine());
            book ezra2 = new book(num2, str4, str3);

            ezer.add(ezra2);
            ezer.add(ezra);

           ezer.printchain();

        }
    }
}

1 Ответ

0 голосов
/ 05 ноября 2018

Ваш цикл в настоящее время выглядит так:

while (this.books.getNext().getValue() != null)
{
    node<book> search = this.books;
    Console.WriteLine(...);
    search = new node<book>(this.books.getNext().getValue(), this.books) ;
}

Похоже, вы пытаетесь перебрать список. Но:

  • Вы продолжаете создавать экземпляр search, но фактически нигде не используете его
  • У вас нет переменной, которая отслеживает, "где в списке я"

Альтернативным подходом может быть использование List<book>. Он поставляется с C # по умолчанию, и затем вы можете перебирать свой список с помощью цикла foreach(book b : this.books). Это избавит вас от необходимости реализовывать собственный класс node<T>.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...