Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

Trying to make a bookshelf console application but having some trouble with lists. (C# Beginner)

I am trying to make a bookshelf application but I am having trouble with using lists. What I am hoping for is after the user specifies how many books they would like to add, the for-loop should hopefully repeat the method in the specified amount.

After the first run through of the method, the more titles added will add onto the list.

    class Shelf
{
    public void Program()
    {
        Book book = new Book();

        int bookAmount;

        Console.WriteLine("How many books are you adding.");
        bookAmount = int.Parse(Console.ReadLine());

        for(int x = 0; x <= bookAmount; x++)
        {
            AddBook(book); 
        }
    }

    public void AddBook(Book book)
    {
        List<string> bookTitles = new List<string>(); 

        string bookTitle;

        Console.WriteLine("Enter title.");
        bookTitle = Console.ReadLine();
        bookTitles.Add(bookTitle);

        bookTitles = book.Title; // 'Cannot implicitly convert type 'string' to 'System.Collections.Generic.List<string>'

    }
}

    class Book
{
    private string title;

    public string Title
    {
        get { return title; }
        set { title = value; }
    }

}

Any critique is welcome. Thank you in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you would want to do would be something like this:

public class Book
{
     public string ISBN { get; set; }
     public string Title {get; set; }
     public string Author {get; set; }
}

The book will represent our data model. Now you would do this:

List<Book> library = new List<Book>();
int quantity;
while(quantity < 7)
{
    library.Add("12345", "C#", "Someone");
}

What the code is doing, we create a List<Book> which will hold our data model. Then you would have a loop that iterates based on value the user inputs. Then you would simply call the library (List) and add after it ask the user for input.

Obviously I'm not attempting to get user input or validation, but is using the example of how to use a List.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...