我有以下两个Java类(在下面列出)Class BookInfo声明数组的静态块

         public class BookInfo {

        // Global arrays accessible by all methods

        private static String[] isbnInfo;
        private static String[] bookTitleInfo;
        private static String[] authorInfo;
        private static String[] publisherInfo;
        private static String[] dateAddedInfo;;
        private static int[] qtyOnHandInfo;
        private static double[] wholesaleInfo;
        private static double[] retailInfo;

        static {

            isbnInfo = new String[] {

                                    "978-0060014018",
                                    "978-0449221431",
                                    "978-0545132060",
                                    "978-0312474881",
                                    "978-0547745527"

                                    };

            bookTitleInfo = new String[] {

                                    "The Greatest Stories",
                                    "The Novel",
                                    "Smile",
                                    "The Bedford Introduction to Drama",
                                    "AWOL on the Appalachian Trail"

                                    };

            authorInfo = new String[]  {

                                     "Rick Beyer",
                                     "James A. Michener",
                                     "Raina Telgemeier",
                                     "Lee A. Jacobus",
                                     "David Miller"

                                    };

            publisherInfo = new String[] {

                                    "HerperResource",
                                    "Fawcett",
                                    "Graphix",
                                    "Bedford St. Martins",
                                    "Mariner Books"

                                    };

            dateAddedInfo = new String[] {

                "05/18/2003",
                "07/07/1992",
                "02/01/2010",
                "09/05/2008",
                "11/01/2011"

                };

            qtyOnHandInfo = new int[] {7, 5, 10, 2, 8};

            wholesaleInfo = new double[] {12.91, 7.99, 6.09, 54.99, 10.17};

            retailInfo = new double[] {18.99, 3.84, 4.90, 88.30, 14.95};

        }

        public static void BookInfo() {

            System.out.println("             Serendipity Booksellers");
            System.out.println("                Book Information\n");


            for(int i = 0; i < isbnInfo.length; i++){

                System.out.println("ISBN: " + isbnInfo[i]);
                System.out.println("Title: " + bookTitleInfo[i]);
                System.out.println("Author: " + authorInfo[i]);
                System.out.println("Publisher: " + publisherInfo[i]);
                System.out.println("Date Added: " + dateAddedInfo[i]);
                System.out.println("Quantity-On-Hand: " + qtyOnHandInfo[i]);
                System.out.println("Wholesale Cost: $ " + wholesaleInfo[i]);
                System.out.println("Retail Price: $ " + retailInfo[i]);
                System.out.println();

            }
        }
        }


如何从此类访问数组列表?到目前为止,只有以下内容有效,但是如何从此类(该类中没有主要的主体)进行修改(添加,删除,编辑等)?BookInfo bookinfo = new BookInfo(); bookinfo.BookInfo(); System.out.println(bookinfo.isbnInfo [0]);如何从主菜单修改(添加,删除,编辑等)

     import java.util.Scanner;

     public class InvMenu {
     public static void addBook(){

      System.out.println("\nYou selected Add a Book\n");
       BookInfo bookinfo = new BookInfo();
      bookinfo.BookInfo(); // only these two are working but I cannot modify arrays at all
      System.out.println(bookinfo.isbnInfo[0]);

        }

       public static void editBook(){

     System.out.println("\nYou selected Edit a Book's Record\n");

     }

     public static void deleteBook(){

      System.out.println("\nYou selected Delete a Book\n");

    }

    public static void printInvMenu(){

    String choice;
    int x = 0;
    boolean b;
    char letter;
    boolean menu = true;

    Scanner keyboard = new Scanner(System.in);

    System.out.println("Serendipity Booksellers");
    System.out.println("Inventory Database\n");
    System.out.println("       1. Look Up a Book");
    System.out.println("       2. Add a Book");
    System.out.println("       3. Edit a Book's Record");
    System.out.println("       4. Delete a Book");
    System.out.println("       5. Return to the Main Menu\n");

    do{

        System.out.print("Enter your choice: ");
        choice = keyboard.nextLine();
        b = true;

        try {
            x = Integer.parseInt(choice);
            System.out.println(x);

        }

        catch(NumberFormatException nFE) {

            b = false;
            System.out.println("You did not enter a valid choice. Try again!\n");

        }

           }while(b == false);

        do{

        else if(x == 1){

            addBook();

        }

        else if(x == 2){

            editBook();

        }

        else if(x == 3){

            deleteBook();

        }

        else if(x == 4){

            System.out.println("Returning to the Main Menu\n");
            break;

        }

        else{

            System.out.println("\nYou did not enter a valid choice. Try again!\n");

        }

        printInvMenu();

       }while(x == 5);

          }
         }


我可以从其他类的主菜单轻松访问某些功能:BookInfo bookinfo = new BookInfo(); bookinfo.BookInfo(); System.out.println(bookinfo.isbnInfo [0]);如何从主菜单修改(添加,删除,编辑等)?任何想法,建议都将不胜感激!

最佳答案

我认为您需要重新考虑一下您的设计。我提供了一个示例,说明了如何使某些功能与您当前的代码一起使用,但是这样做会创建一些严重的令人讨厌的代码。

静态通常用于在实例之间共享信息,实例中此信息是唯一的。通常的示例是作为实例计数器。因此,每次创建实例时,它都会增加值,以便您可以跟踪唯一的实例。

问题是bookInfo不知道它不是什么意思。它既要成为数据存储,又要描述一个唯一的对象。想想如果要创建另一个BookInfo会发生什么。编辑一个实例的任何静态都会影响其他实例。

您可以轻松地在静态String []中编辑信息。

public int getBookLocation(Sting name){
    return bookTitleInfo.IndexOf(name)
}


然后,您可以根据需要操纵特定的条目。

public void SetBookName(String oldname, String newname){
    int index = getBookLocation(oldname);
    if(index > 0){
        bookTitleInfo[index] = newname;
}


这对于编辑来说还算不错,但是删除条目将非常混乱。这是一些伪代码

first have to find the bookindes. - getBookLocation(...)

For each entry in static string[]
    create a new one of size-1,
        For each entry in String[]
            add existing entry to new string[].


您需要为每个阵列执行此操作。即isbnInfo,bookInfoName,....,
那是很多不必要的迭代。



以下内容虽然不能解决您的问题,但却是一种更好的设计方法,可以将关注点分为几类。


一类应该代表您的Book对象。此类将提供存储/设置/检索单个书本对象的所有数据的功能。
另一个将代表书店,该书店将存储书对象列表,用书初始化数据,提供从商店中添加,删除,编辑书的功能。

公共类BookInfo {

//Class variables
private String isbnInfo;
private String bookTitleInfo;
//....
private double wholesaleInfo;
private double retailInfo;

//Constructors
BookInfo(){
    //put default behaviour here
}

BookInfo(String isbnInfo, String bookTitleInfo, .....){
    this.isbnInfo = isbnInfo;
    this.bookTitleInfo = bookTitleInfo;
    this.authorInfo = authorInfo;

    //....


//Setter Method
public String getIsbnInfo(){
    return isbnInfo;
}

//Getter Method
public void setBookTitleInfo(String isbnInfo){
    this.isbnInfo = isbnInfo;
}

//.....



因此,现在您可以创建一个Book信息并设置/获取其所有变量(以OOP方式封装)。

接下来,我们将研究BookInfos的存储/访问类。

public class BookStore {
    private isbnInfo = new String[] {"978-0060014018", "978-0449221431", "978-0545132060",
                                "978-0312474881", "978-0547745527" };

    private bookTitleInfo = new String[] { "The Greatest Stories", "The Novel", "Smile",
                                "The Bedford Introduction to Drama",
                                 "AWOL on the Appalachian Trail" };

    //...rest of strings

    //here is where we store our book objects
    //we will create methods to add, remove, edit, later
    private BookInfo booklist = new List<BookInfo>();
    private String storename;

    //Default Constructor initialises booklist based on stored values
    public BookStore(){
         for(int i = 0; i < isbnInfo.lenght; i++){
             AddBook(isbnInfo [i], bookTitleInfo[i],.....,retailInfo[i]);
         )
    }

    //overloaded constructors you probably want to read from external file, db etc eventually.
    public BookStore(String filelocation){
         //Do stuff to read from a file and add books to booklist
    }

    //Add a new book to the list by passing in all the info
    public void AddBook(String isbn, String title,
         BookInfo newbook = new BookInfo(isbn, title, ....)
         booklist.add(newbook);

    //Add a new book by passing in a book object.
    public void AddBook(BookInfo newbook){
         booklist.add(newbook);
    }

    //Find Book
    public int getBook(String isbn){
        for(int i=0; i++; i < booklist.lenght){
            if(book.getIsbn() == isbn)
                return i;
        }
        return -1;

    //Remove Book from list
    public void removeBook(String isbn){
         int loc = getbook(isbn);
         if(loc > -1){
             booklist.remove(loc);
         }
         else{
             System.out.println(Could not find book);
         }
    }

    public void DisplayBookList(){
    //.. print list
    }
}


因此,现在BookStore需要的所有必需功能都位于所需的位置。现在,您可以根据需要添加任何其他功能。

您的主驱动程序类也将需要更改。您的驱动程序类需要创建BookStore。

如果用户想删除一本书,则可以输入“书名”。然后你打电话

bookstore.removeBook(userstring);


添加一本书需要用户输入更多的值,但本质上是相同的

String isbn = scanner.next();
String bookname = scanner.next();
.......
double wholesaleinfo = Double.ParseDouble(scanner.next());


然后,您可以通过将信息作为参数传递来添加罐头

bookstore.addBook(isbn, bookname, ...., wholesaleinfo);


或书籍对象。

BookInfo newbook = new BookInfo(isbn, bookname, ...., wholesaleinfo)
bookstore.addBook(newbook);


我会将用户逻辑留给您想要的任何方式。希望那已经说明了事情。当然,可以对我所做的事情进行改进。

10-08 12:57