简体   繁体   中英

Creating Java Classes

I am currently working on an inventory program involving a one dimensional array, 2 classes (Store and Book), and several other things such as methods and a constructor.

The Store class which is the main class I guess you could say is supposed to include the main() method, and is supposed to read a list of purchases from a file, process each purchase with an appropriate message (ISBN number, amount, price, or problem (such as out of stock or do not have)), store an array of up to 15 books of type Book, a method to read in the inventory file, method to process a purchase, a method to print the inventory at closing along with the number of books sold and amount made at closing.

The Book class includes, book objects (each book object holds ISBN String, price double, and copies int), constructor, getters and setters, and a method to print the information.

Since the array is supposed to be created in the Store class, but be of type Book and made up of the book objects (I'm assuming?), I'm having trouble figuring out how to do this properly (assigning values to the isbn, price, copies variables, setting up the constructor correctly, etc).

Update The main issue I'm having right now is being able to print the book object from my printInfo method. I am getting an error message at the print statement of that method stating "cannot find symbol. symbol: book". I can't really see if the program is actually working yet since that's kind of what I need to see at this point (the printed out book object) before I start adding in a few more methods to do other things that depend on this book object being correct.

Here is the code I have come up with so far:

The Store class:

import java.util.Scanner;
import java.io.*;

public class Store {
    public static void main(String[] args) throws Exception {
        Book[] books = readInventory();

        for (Book : books) {
            System.out.printf("ISBN: %s, Price: %f, Copies: %d%n",
            book.getISBN(), book.getPrice(), book.getCopies()); 
        }
    }

    public static Book[] readInventory() throws Exception {
        Book[] books = new Book[15];
        java.io.File file = new java.io.File("../instr/prog4.dat");
        Scanner fin = new Scanner(file);
        String isbn;
        double price;
        int copies;

            while (fin.hasNext()) {
                for(int i = 0; i < books.length; i++) {
                isbn = fin.next();
                price = fin.nextDouble();
                 copies = fin.nextInt();

                 Book book = new Book(isbn, price, copies);
                 books[i] = book;
                }
            }
            fin.close();
            return books;
    }

    public static void printInfo(Book[] books) {
        System.out.println(book);
    }
}

And here is my Books Class:

public class Book {
    private String isbn;
    private double price;
    private int copies;

    public Book(String isbnNum, double priceOfBook, int copiesInStock) {
        isbn = isbnNum;
        price = priceOfBook;    
        copies = copiesInStock;
    }

    public String getISBN() {
        return isbn;
    }

    public double getPrice() {
        return price;
    }

    public int getCopies() {
        return copies;
    }

    public void setISBN(String isbn) {
        this.isbn = isbn;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public void setCopies(int copies) {
        this.copies = copies;
    }

    @Override
    public String toString() {
        return String.format("ISBN: %s, Price: %f, Copies: %d%n",
                this.getISBN(), this.getPrice(), this.getCopies());
    }
}

This is my first time working with classes, or at least creating multiple classes in the same program, so I'm still trying to figure out how this works. I've been reading a tutorial I found online that has been somewhat helpful, but I'm having trouble applying it to this specific type of program.

Any suggestions would be greatly appreciated.

Hi glad to see you've made the effort to actually try something before jumping on here. What you have done is pretty good so far. But what you really need now is a getter and setter method in your class Book . These will allow you to return or set the value of the variable for the object.

public class Book {
    private String isbn;
    private double price;
    private int copies;

    public Book(String isbnNum, double priceOfBook, int copiesInStock) { // Constructor?
        isbn = isbnNum;
        price = priceOfBook;
        copies = copiesInStock;
    }

    public String getISBN() {
        return this.isbn;
    }

    public double getPrice() {
        return this.price;
    }

    public int getCopies() {
        return this.copies;
    }

    public void setISBN(String value) {
        this.isbn = value;
    }

    public void setPrice(double value) {
        this.price = value;
    }

    public void setCopies(int value) {
        this.copies = value;
    }
}

This should help you get on the right track. Depending on how you want the information to come up would depend on whether you add System.out.println("ISBN: " + this.isbn); and so on in each get function, or you could declare a separate function getInfo which simply prints each. Or if you were returning it into store you could always print it that way. One more thing to note is that you have been declaring books as Book[] books = new Book[15] as you are creating an array of Book objects and not strings. If you need any more help let me know.

1.you shouldn't use String Array.you should declare Book Array instead. then It will be easier to assign your Book object.

for example Book[] books = new Book[15]; books[i] = new Book(isbnNum,priceOfBook,copiesInStock);

2.because variable in Book class was declare in private type. you should create get methods in your Book class to get variable in any object.

for example

public String getbnNum()
{
return isbn;
}

public double getprice(){
return price;
}

public int getcopies(){
return copies;
}

I wrote comments in the code for you. I have to assume your file-reading code is correct since I don't have the file.

import java.util.Scanner;

public class Store {

    /* 
     * This is the main method. It is where the code that starts off the
     * application should go.
     */
    public static void main(String[] args) throws Exception {
        // Here, we take the array returned by the method and set it to a local variable.
        Book[] books = readInventory();

        // This is an alternative notation than a normal for-loop.
        for (Book book : books) {
            System.out.printf("ISBN: %s, Price: %f, Copies: %d%n",
                    book.getISBN(), book.getPrice(), book.getCopies());
        }

    /* Alternative to above.
        for (int i = 0; i < books.length; i++) {
            Book book = books[i];
            System.out.printf("ISBN: %s, Price: %f, Copies: %d%n",
                    book.getISBN(), book.getPrice(), book.getCopies());
        }
    */
    }

    // We add the return type of Book[] so we can get a reference to our array.
    public static Book[] readInventory() throws Exception {
        Book[] books = new Book[15];
        java.io.File file = new java.io.File("../instr/prog4.dat");
        Scanner fin = new Scanner(file);

        // These variables don't need to be initialized yet.
        String isbn;
        double price;
        int copies;

        while (fin.hasNext()) {

            // Fill the books array with Book objects it creates from the file.
            for (int i = 0; i < books.length; i++) {
                isbn = fin.next();
                price = fin.nextDouble();
                copies = fin.nextInt();

                Book book = new Book(isbn, price, copies);
                books[i] = book;
            }
        }
        fin.close();
        return books;
    }
}

Book class:

public class Book {
    private String isbn;

    /*
     * Careful using double as your type for variables that hold money values.
     * If you do any division, you can end up getting answers different than
     * what you might expect due to the way Java handles remainders. For that,
     * make price a Currency type, which you can import from Java.util
     */
    private double price;

    private int copies;

    public Book(String isbnNum, double priceOfBook, int copiesInStock) {
        isbn = isbnNum;
        price = priceOfBook;
        copies = copiesInStock;
    }

    // This is an example of a getter method, which we need since our isbn is
    // declared as private. Now, other methods can still read what isbn is.
    public String getISBN() {
        return isbn;
    }

    public double getPrice() {
        return price;
    }

    public int getCopies() {
        return copies;
    }

    /*
     * We can use the "this" keyword to refer to this instance's isbn variable,
     * instead of the local variable isbn that was passed to the method.
     * Therefore, in this tricky notation we are setting the object's isbn
     * variable to the isbn variable passed to the method.
     */
    public void setISBN(String isbn) {
        this.isbn = isbn;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public void setCopies(int copies) {
        this.copies = copies;
    }
}

Also note that a more advanced way to print the information for each book would be to make a toString() method in the Book class which overrides the default toString method it inherits from the generic Object class. You should use a special convention called an override annotation to do this as it is considered good practice when we redefine methods from a superclass ( Object is a superclass of all objects, including Book ).

@Override
public String toString() {
    return String.format("ISBN: %s, Price: %f, Copies: %d%n",
            this.getISBN(), this.getPrice(), this.getCopies());
}

That would allow us to simply call System.out.println(book); , for example, and would also mean we wouldn't have to rewrite all of this code every place we want to print a book. This is an important principle with objects—they generally should take care of themselves.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM