// Lecture 4 // CS U213 Fall 2008 // bookstore-methods1.java /* ;; A Book is (make-book String String Num Symbol) ;; There are three kinds of books: fiction, nonfiction, textbook ;; represented by symbols 'F 'N 'T (define-struct book (title author price kind)) ;; Examples of books (define oms (make-book "Old Man and the Sea" "EH" 10 'F)) (define eos (make-book "Elements of Style" "EBW" 20 'N)) (define htdp (make-book "HtDP" "MF" 60 'T)) */ /* +---------------+ | Book | +---------------+ | String title | | String author | | int price | | char kind | +---------------+ */ // to represent a book in a bookstore class Book{ String title; String author; int price; char kind; Book(String title, String author, int price, char kind){ this.title = title; this.author = author; this.price = price; this.kind = kind; } /* TEMPLATE: ... this.title ... -- String ... this.author ... -- String ... this.price ... -- int ... this.kind ... -- char ... this.writtenBy(String) ... -- boolean ... this.salePrice() ... -- int ... this.sameAuthor(Book) ... -- boolean */ // was this book written by the given author? boolean writtenBy(String author){ return this.author.equals(author); } /* the sale price of the book depends on the daily discounts these may differ depending on the kind of book suppose today we have the following discounts: there is 30% discount on fiction books there is 20% discount on nonfiction books textbooks sell at full price */ // compute the discounted sale price for this book int salePrice(){ if (this.kind == 'F'){ return this.price - 3 * (this.price / 10); } else {if (this.kind == 'N'){ return this.price - 2 * (this.price / 10); } else { return this.price; }} } // was this book written by the same author as the given book? boolean sameAuthor(Book that){ return this.author.equals(that.author); } } class Examples{ Examples(){} Book oms = new Book("Old Man and the Sea", "EH", 10, 'F'); Book eos = new Book("Elements of Style", "EBW", 20, 'N'); Book htdp = new Book("HtDP", "MF", 60, 'T'); Book ll = new Book("LL", "MF", 20, 'N'); // test the method writtenBy in the class Book boolean testWrittenBy = (check this.oms.writtenBy("EH") expect true) && (check this.eos.writtenBy("EH") expect false) && (check this.htdp.writtenBy("MF") expect true); // test the method salePrice in the class Book boolean testSalePrice = (check this.oms.salePrice() expect 7) && (check this.eos.salePrice() expect 16) && (check this.htdp.salePrice() expect 60); // test the method sameAuthor in the class Book boolean testSameAuthor = (check this.oms.sameAuthor(this.eos) expect false) && (check this.eos.sameAuthor(this.ll) expect false) && (check this.htdp.sameAuthor(this.ll) expect true); }