Ian Chen 發問時間: 電腦與網際網路程式設計 · 8 年前

java problem hurry!!!!

4. Let us assume that a newer, larger edition of book2 is published. Write statements that could be used in the main method of the application class to do the following:

a. Change the number of pages of book2 to 50 more than you initially specified (Hint: Use your method to retrieve the number of pages).

b. Compute the production cost, using the per-page cost of $0.02, and assign the new cost to a variable named newBookCost. Display the new cost, along with explanatory text.5. Define an array of Books, named library, with a size of 3. Place the first book you created in position [0] of the array, and the second book you created in position [1] of the array. Use a counter to keep track of the number of books stored in the array. 6. Using a for-loop, write the statements which would display only the titles of all the books in the array library. Write your code in such a way to avoid generating a exception.

1 個解答

評分
  • 8 年前
    最佳解答

    請參考我的做法

    class MyBook {

    private String title;

    private int pages;

    MyBook(String t, int p) {

    title = t; pages = p;

    }

    String getTitle() { return title; }

    void setTitle(String s) { title = s; }

    int getPages() { return pages; }

    void setPages(int p) { pages = p; }

    @Override

    public String toString() { return title + "[" + pages + "]"; }

    public double prodCost(double base) {

    return base * pages + ((pages > 300) ? 2.0D : 0);

    }

    }

    public class Y0393 {

    public static void main(String[] args) {

    MyBook book1 = new MyBook("How to Build a PC", 400);

    MyBook book2 = new MyBook("Inception", 289);

    System.out.println("Book 1 Title: " + book1.getTitle());

    System.out.println("Book 1 Pages: " + book1.getPages());

    System.out.println("Book 1 Production Cost: " + book1.prodCost(0.03D));

    book2.setPages(book2.getPages() + 50);

    double newBookCost = book2.prodCost(0.02D);

    System.out.println("New Book 2 Production Cost: " + newBookCost);

    MyBook[] library = new MyBook[3];

    library[0] = book1;

    library[1] = book2;

    int counter = 2;

    for (int i = 0; i < counter; i++) {

    System.out.println(library[i].getTitle());

    }

    }

    }

還有問題?馬上發問,尋求解答。