How do I fix "cannot find symbol" error? - java

i get three error message on my BookTest class and it says cannot find symbol on getCode(), getCategory, and calculateTax. how do i fix this? im trying to print these out in a dialog box but these three are the only ones not working.
import javax.swing. JOptionPane;
public class BookTest
{
public static void main(String args[])
{
double charge;
double grandTotal= 0;
String dataArray[][] = {{"NonFiction", "Abraham Lincoln Vampire Hunter","Grahame-Smith","978-0446563079","13.99","Haper","NY","US","Political"},
{"NonFiction", "Frankenstein","Shelley","978-0486282114","7.99","Pearson", "TX","England", "Historical"},
{"Fiction", "Dracula","Stoker","978-0486411095","5.99","Double Day", "CA","4918362"},
{"NonFiction", "Curse of the Wolfman"," Hageman","B00381AKHG","10.59","Harper", "NY","Transylvania","Historical"},
{"Fiction", "The Mummy","Rice","978-0345369949","7.99","Nelson","GA","3879158"}};
Book bookArray[] = new Book[dataArray.length];
int quantityArray[] = {12, 3, 7, 23, 5};
for (int i = 0; i < dataArray.length; i++)
{
if (dataArray[i][0] == "NonFiction")
{
bookArray[i] = new NonFictionBook(dataArray[i][1], dataArray[i][2], dataArray[i][3], Double.parseDouble(dataArray[i][4]),
new Publisher(dataArray[i][5], dataArray[i][6]), dataArray[i][7], dataArray[i][8]);
}
else
{
bookArray[i] = new FictionBook(dataArray[i][1], dataArray[i][2], dataArray[i][3], Double.parseDouble(dataArray[i][4]),
new Publisher(dataArray[i][5], dataArray[i][6]), Integer.parseInt(dataArray[i][7]));
}
}
String msg = "";
for (int i = 0; i < bookArray.length; i++)
{
charge = bookArray[i].calculateTotal(quantityArray[i]);
grandTotal = charge + grandTotal;
msg += String.format("%s %s %d $%.2f $%.2f\n", bookArray[i].getTitle(), bookArray[i].getCategory(), bookArray[i].getCode(), bookArray[i].calculateTax, charge); //this is where i get the 3 error messages. im trying to print all in one dialog box the title, category of the book, charge and tax for each book.
}
msg += String.format("Grand Total $%.2f ", grandTotal);
JOptionPane.showMessageDialog(null, msg);
}
}
**************************************************************
public abstract class Book implements Tax
{
private String title;
private String author;
private String isbn;
private Double price;
private Publisher publisher;
public Book()
{
setTitle("");
setAuthor("");
setIsbn("");
setPrice(0.0);
setPublisher(new Publisher());
}
public Book(String t, String a, String i, double p, Publisher n)
{
setTitle(t);
setAuthor(a);
setIsbn(i);
setPrice(p);
setPublisher(n);
}
public void setTitle(String t)
{
title = t;
}
public String getTitle()
{
return title;
}
public void setAuthor(String a)
{
author = a;
}
public String getAuthor()
{
return author;
}
public void setIsbn(String i)
{
isbn = i;
}
public String getIsbn()
{
return isbn;
}
public void setPrice(double p)
{
price = p;
}
public double getPrice()
{
return price;
}
public void setPublisher(Publisher n)
{
publisher = n;
}
public Publisher getPublisher()
{
return publisher;
}
public abstract double calculateTotal(int quantity);
public double calculateTax(double a)
{
return a * .08;
}
public String toString()
{
return( " Title " + title + " Author " + author + " Isbn " + isbn
+ " Price " + price + " Publisher " + publisher.toString());
}
}
********************************************************
public class NonFictionBook extends Book
{
private String country;
private String category;
public NonFictionBook()
{
super();
setCountry("");
setCategory("");
}
public NonFictionBook(String t, String a, String i, double p, Publisher n, String c, String ca)
{
super(t,a,i,p,n);
setCountry(c);
setCategory(ca);
}
public void setCountry(String c)
{
country = c;
}
public void setCategory(String ca)
{
category = ca;
}
public String getCountry()
{
return country;
}
public String getCategory()
{
return category;
}
public String toStirng()
{
return( super.toString() + "Country " + country + " Category " + category);
}
public double calculateTotal(int quantity)
{
double charge =0;
charge = (quantity * getPrice());
if( country != "US" )
charge += 50;
return charge;
}
}
*********************************************
public class FictionBook extends Book
{
private int code;
public FictionBook()
{
super();
setCode(0);
}
public FictionBook(String t, String a, String i, double p, Publisher n, int c)
{
super(t,a,i,p,n);
setCode(c);
}
public void setCode(int c)
{
code = c;
}
public int getCode()
{
return code;
}
public String toString()
{
return (super.toString() + " Code " + code);
}
public double calculateTotal(int quantity)
{
double charge =0;
charge = (quantity * getPrice());
if (quantity > 5)
charge += 5 * (quantity - 5);
return charge;
}
}

The tree methods are implemented in subclasses of Books. So you have to cast the value to the subclass.
if (bookArray[i] instanceof FictionBook){
FictionBook fb = (FictionBook)bookArray[i];
msg += String.format("%s %s %d $%.2f $%.2f\n", fb.getTitle(), "", fb.getCode(), 0, charge);
}
if (bookArray[i] instanceof NonFictionBook){
NonFictionBook fb = (NonFictionBook)bookArray[i];
msg += String.format("%s %s %d $%.2f $%.2f\n", nfb.getTitle(), nfb.getCategory(), nfb.getCode(), nfb.calculateTax, charge);
}
and so on
Also you have to use equals() for comparing string. Not ==

In the line you get error you try to print fields that are not instances of the Book class but of its subclasses.
You got an array of Books, you iterate on them and try to print the information. But not all the Books have getCode() method (only the fiction books) and only the non fiction books have getCategory() method. So you can't do this for ALL books.
You can change your print depending on the book type or you can make a method in Book class and each subclass can override it that prints the information you have for this class (like the toString method). Then use that in the main class.
And also as pointed in comments test if strings are equal with equals operator and not == or !=

Your array uses the type book:
Book bookArray[] = new Book[dataArray.length];
Later, you add sub-classes into this array, like NonFictionBook. Since code, category etc. are only part of the sub-classes, you cannot access them using the Book array reference.
// won't work because class Book does not have these methods, properties
bookArray[i].getCategory(), bookArray[i].getCode(), bookArray[i].calculateTax
You need to cast the object (based on what type is in the array).

Related

How to get rid of syntax error on token "public" in main class?

I am getting a syntax error in my main class when I call the constructor from another class that I need for the main program to run. This program is focused on inheritance and the appropriate calling of constructors and arguments. This is the error message I get during compilation:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error on token "public", record expected after this token
at a6main.main(a6main.java:7)
This is the line of code that is causing the error:
PreferredCustomer c = new PreferredCustomer("Al", "222BurdSt", "2102223321", "46821",
"2000", true, "1000");
The rest of the code can be found below:
class person {
String Name;
String Address;
String Telephone;
person (String Name, String Address, String Telephone) {
this.Name = Name;
this.Address = Address;
this.Telephone = Telephone;
}
String getName() {
return Name;
}
String getAddress() {
return Address;
}
String getTelephone() {
return Telephone;
}
void setName(String Name) {
this.Name = Name;
}
void setAddress(String Address) {
this.Address = Address;
}
void setTelephone(String Telephone) {
this.Telephone = Telephone;
}
}
public class customer extends person {
String number;
boolean OnMailingList;
//constructor and getters and setters
customer (String Name, String Address, String Telephone, String number, boolean OnMailingList) {
//inherit persons information
super(Name, Address, Telephone);
this.number = number;
this.OnMailingList = OnMailingList;
}
String getnumber() {
return number;
}
void setnumber(String number) {
this.number = number;
}
boolean OnMailingList () {
return OnMailingList;
}
void setOnMailingList(boolean OnMailingList) {
this.OnMailingList = OnMailingList;
}
}
public class PreferredCustomer extends customer {
private int purchase;
double discount;
/**public constructor so its accessible to main
* else ifs for certain percentage of discounts
* getters and setters for purchase and discount
* super to inherit other features from other classes */
public int getpurchase() {
return purchase;
}
public double getdiscount () {
return this.discount;
}
public void setPurchase(int purchase) {
this.purchase = purchase;
}
public PreferredCustomer(String Name, String Address, String Telephone, String number, int pur,
boolean OnMailingList, double Discount, PreferredCustomer preferredCustomer) {
super(Name, Address, Telephone, number, OnMailingList);
this.purchase = pur;
preferredCustomer.discount = discount;
if (this.purchase>= 2000) {
this.discount = 10;
} else if (this.purchase>= 1500) {
this.discount = 7;
} else if (this.purchase>= 1000) {
this.discount = 6;
} else if (this.purchase >= 500) {
this.discount = 5;
}
}
}
public class a6main {
public static void main (String [] args) {
public PreferredCustomer() {
}
PreferredCustomer c = new PreferredCustomer("Al", "222BurdSt", "2102223321", "46821","2000", true, "1000");
System.out.println("Name: " + c.getName());
System.out.println("Address: " + c.getAddress());
System.out.println("Telephone number: " + c.getTelephone());
System.out.println("Customer ID: " + c.getnumber());
System.out.println("Amount spent: " + c.getpurchase());
System.out.println("On mailing list: " + c.OnMailingList());
System.out.println("Discount: " + c.getdiscount());
}
}
You have several mistakes here. I've corrected them, and the program launches, providing the result:
Name: Al
Address: 222BurdSt
Telephone number: 2102223321
Customer ID: 46821
Amount spent: 2000
On mailing list: true
Discount: 10.0
Remove PreferredCustomer constructor from the main method. It can't be a part of a
method, it is a part of a class. Then, the constructor for PreferredCustomer is already present in PreferredCustomer class.
Hopefully, your customer and PreferredCustomer classes are in separate files? If not, put them in separate files named customer.java and PreferredCustomer.java. In PreferredCustomer class constructor, remove PreferredCustomer preferredCustomer from arguments. It's redundant: why you need to pass one customer into another? Do customers have any relationships with each other? Now the number of arguments will match when you call the constructor (and don't use strings "2000", "1000" where should be integers):
PreferredCustomer c = new PreferredCustomer("Al", "222BurdSt", "2102223321", "46821",
2000, true, 1000);
Further in the PreferredCustomer constructor, use this instead of preferredCustomer here: this.discount = Discount; and print Discount with upper case, as in the signature of the constructor.
As a result, the code of the constructor should be:
public PreferredCustomer(String Name, String Address, String Telephone, String number, int pur, boolean OnMailingList, double Discount) {
super(Name, Address, Telephone, number, OnMailingList);
this.purchase = pur;
this.discount = Discount;
if (this.purchase>= 2000) {
this.discount = 10;
} else if (this.purchase>= 1500) {
this.discount = 7;
} else if (this.purchase>= 1000) {
this.discount = 6;
} else if (this.purchase >= 500) {
this.discount = 5;
}
}
The main method in a6main class:
public static void main (String [] args) {
PreferredCustomer c = new PreferredCustomer("Al", "222BurdSt", "2102223321", "46821", 2000, true, 1000);
System.out.println("Name: " + c.getName());
System.out.println("Address: " + c.getAddress());
System.out.println("Telephone number: " + c.getTelephone());
System.out.println("Customer ID: " + c.getnumber());
System.out.println("Amount spent: " + c.getpurchase());
System.out.println("On mailing list: " + c.OnMailingList());
System.out.println("Discount: " + c.getdiscount());
}
And take care of naming conventions, as other people pointed.

Making a class-array dynamic in Java

I've created a Java class called 'Book'. Using this class I'm willing to update information about a new object 'book1'. I'm also wanting to add Author information into the object 'book1'. So, I've dynamically allocated memory using a class-array called 'Author[ ]'. By this I mean there's a separate code in which I've created a class called 'Author' with its own set of instance variables. I'm not getting into that now. However, when I'm testing the class 'Book' using another class called 'TestBook' there's no compilation error BUT I'm getting the following message in the console window when I'm running the code:
Exception in thread "main" java.lang.NullPointerException
at Book.addAuthors(Book.java:34)
at TestBook.main(TestBook.java:12)
The code for 'Book' is shown below:
public class Book {
private String name;
private Author[] A = new Author[];
private int numAuthors = 0;
private double price;
private int qtyInStock;
public Book(String n, Author[] authors, double p) {
name = n;
A = authors;
price = p;
}
public Book(String n, Author[] authors, double p, int qIS) {
name = n;
A = authors;
price = p;
qtyInStock = qIS;
}
public Book(String n, double p, int qIS) {
name = n;
price = p;
qtyInStock = qIS;
}
public String getName() {
return name;
}
/*
public Author getAuthors() {
return A;
}
*/
public void addAuthors(Author newAuthor) {
A[numAuthors] = newAuthor; // THIS LINE IS WHERE THE ERROR POINTS TO
++numAuthors;
}
public void printAuthors() {
/*
for (int i = 0; i < A.length; i++) {
System.out.println(A[i]);
}
*/
for (int i = 0; i < numAuthors; i++) {
System.out.println(A[i]);
}
}
public void setPrice(double p) {
price = p;
}
public double getPrice() {
return price;
}
public void setqtyInStock(int qIS) {
qtyInStock = qIS;
}
public int getqtyInStock() {
return qtyInStock;
}
/*
public String getAuthorName() {
return A.getName();
}
public String getAuthorEmail() {
return A.getEmail();
}
public char getAuthorGender() {
return A.getGender();
}
*/
public String toString() {
/*
return getName() + " " + getAuthor() + " Book price: " + getPrice() +
" Qty left in stock: " + getqtyInStock();
*/
//return getName() + " is written by " + A.length + " authors.";
return getName() + " is written by " + numAuthors + " authors.";
}
}
The code for 'TestBook' is shown below:
public class TestBook {
public static void main(String args[]) {
//Author[] authors = new Author[2];
//authors[0] = new Author("Tapasvi Dumdam Thapashki", "tapasvi#thapashki.com", 'M');
//authors[1] = new Author("Paul Rand", "paulie#aol.com", 'M');
Book book1 = new Book("The Quickie Man", 69.00, 5);
//System.out.println(book1.toString());
//book1.setqtyInStock(5);
//System.out.println(book1.toString());
//System.out.println(book1.getAuthorName() + " " + book1.getAuthorEmail());
//book1.printAuthors();
book1.addAuthors(new Author("Linda Lee", "lindalee#grinchtown.com", 'F'));
book1.addAuthors(new Author("Joseph Caputo", "caputo#lfp.com", 'M'));
System.out.println(book1.toString());
book1.printAuthors();
}
}
The code for 'Author' is shown below:
public class Author {
private String name;
private String email;
private char gender;
public Author(String n, String e, char g) {
name = n;
email = e;
gender = g;
}
public String getName() {
return name;
}
public void setEmail(String e) {
email = e;
}
public String getEmail() {
return email;
}
public char getGender() {
return gender;
}
public String toString() {
return getName() + " [" + getGender() + "] " + getEmail();
}
}
I'd like some help with this.
Initialize Author array with proper size like private Author[] A = new Author[4];
You forgot to specify the size of the Array.
private Author[] A = new Author[15];
For making a dynamic array you can use ArrayList.
private ArrayList<Author> list = new ArrayList<Author>();
addAuthors()
public void addAuthors(Author newAuthor) {
list.add(newAuthor);
}
printAuthors()
public void printAuthors() {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}

Java calling a subclass from a class using a different java file and class

I have this main java file:
public class GroceryBill {
private Employee clerk;
private List<Item> receipt;
private double total;
private double internalDiscount;
public GroceryBill(Employee clerk) {
this.clerk = clerk;
receipt = new ArrayList<Item>();
total = 0.0;
internalDiscount = 0.0;
}
public void add(Item i) {
receipt.add(i);
total += i.getPrice();
internalDiscount += i.getDiscount();
}
public double getTotal() {
return Math.rint(total * 100) / 100.0;
}
public Employee getClerk() {
return clerk;
}
public void printReceipt() {
System.out.println(this);
}
private String valueToString(double value) {
value = Math.rint(value * 100) / 100.0;
String result = "" + Math.abs(value);
if(result.indexOf(".") == result.length() - 2) {
result += "0";
}
result = "$" + result;
return result;
}
public String receiptToString() {
String build = "items:\n";
for(int i = 0; i < receipt.size(); i++) {
build += " " + receipt.get(i);
if(i != receipt.size() - 1) {
build += "\n";
}
}
return build;
}
public String toString() {
return receiptToString() + "\ntotal: " + valueToString(total);
}
public String discountToString() {
return receiptToString() + "\nsub-total: " + valueToString(total) + "\ndiscount: " + valueToString(internalDiscount) + "\ntotal: " + valueToString(total - internalDiscount);
}
public static class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public static class Item {
private String name;
private double price;
private double discount;
public Item(String name, double price, double discount) {
this.name = name;
this.price = price;
this.discount = discount;
}
public double getPrice() {
return price;
}
public double getDiscount() {
return discount;
}
private String valueToString(double value) {
String result = "" + Math.abs(value);
if(result.indexOf(".") == result.length() - 2) {
result += "0";
}
result = "$" + result;
return result;
}
public String toString() {
return name + " " + valueToString(price) + " (-" + valueToString(discount) + ")";
}
}
// REPLACEME
}
I want to call and be able to use getDiscount() and etc from the "Item" subclass, but I can't figure out how to access it in a different file + class that extends GroceryBill.
public class DiscountBill extends GroceryBill {
    
    private int myCount;
    private double myDiscount;
    private double myPrice;
    private String myName;
    
    public DiscountBill(Employee clerk, boolean preferred) {
        super(clerk);
String name = "";
double price = 0;
double discount = 0;
        GroceryBill.Item myBill = new GroceryBill.Item(name, price, discount);
Object myItem = new Item(name, price, discount);
        myDiscount = myBill.getDiscount();
        myPrice = ((GroceryBill.Item) myItem).getPrice();
        if (preferred && myDiscount > 0.0) {
            myCount++;
        }
    }
    
    public int getDiscountCount() {
        return myCount;
    }
    
    public double getDiscountAmount() {
        return myDiscount;
    }
    
    public double getDiscountPercent() {
        return (myPrice / getDiscountCount()) * 100;
    }
    
}
Here is my class that is in a different java file that extends the original one. How would I call methods from the Item subclass that belongs to the GroceryBill class?
You can do like
Create object to super class using that object try to create object for its sub class.
for example:
public class Sample {
class InnerClass
{
public void foo()
{
System.out.println("Helolo");
}
}
}
Base class is :
public class BaseClass extends Sample {
public static void main(String[] args) {
Sample sObj = new Sample();
Sample.InnerClass innerObj = sObj.new InnerClass();
innerObj.foo();
}
}
You can follow this approach to call inner class methods
To access inner static classes :
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
In your case just add statement like :
GroceryBill.Item = new GroceryBill.Item(name, price, discount);

Need help making a relationship work with (2) classes

I am trying to verify what is wrong with my class builds to make address class communicate with my warehouse class. My get() and set methods along with toString() is in question. Any help would be greatly appreciated
public class Address
{
private String street;
private String city;
private String state;
private int zip;
public Address()
{
setStreet("");
setCity("");
setState("");
setZip(0);
}
public Address(String str, String c, String sta, int z)
{
setStreet(str);
setCity(c);
setState(sta);
setZip(z);
}
public String getStreet()
(
return street;
}
public String getCity()
{
return city;
}
public String getState()
{
return state;
}
public int getZip()
{
return zip;
}
public void setStreet( String str)
{
street = str;
}
public void setCity( String c)
{
city = c;
}
public void setState( String sta )
{
state = sta;
}
public void setZip( String z )
{
zip = z;
}
public String toString()
{
return( " Street " + street + " City " + city +" State " + state + " Zip " + zip);
}
}
Must communicate with the following warehouse class:
public class Warehouse
{
private double squareFeetSize;
private double pricePerSquareFoot;
private int televisions;
private int computers;
private Address address;
public Warehouse()
{
setSquareFeetSize(0.0);
setPricePerSquareFoot(0.0);
setTelevisions(0);
setComputers(0);
setAddress(new Address());
}
public Warehouse( double s, double p, int t, int c, Address a)
{
setSquareFeetSize(s);
setPricePerSquareFoot(p);
setTelevisions(t);
setComputers(c);
setAddress(a);
}
public double getSquareFeetSize()
{
return squareFeetSize;
}
public double getPricePerSquareFoot()
{
return pricePerSquareFoot;
}
public int getTelevisions()
{
return televisions;
}
public int getComputers()
{
return computers;
}
public Address getAddress()
{
return address;
}
public void setSquareFeetSize( double s)
{
squareFeetSize = s;
}
public void setPricePerSquareFoot ( double p )
{
pricePerSquareFoot = p;
}
public void setTelevisions ( int t )
{
televisions = t;
}
public void setComputers ( int c)
{
computers = c;
}
public void setAddress( Address a)
{
address = a;
}
public String toString()
{
return (" Square Foot Size " + squareFeetSize + " Price Per Square Foot " +
pricePerSquareFoot + " Televisions " + televisions + " Computers " +
computers + " Address " + address.toString());
}
public double calculateWarehouseCharge()
{
double charge = 0.0;
charge = (squareFeetSize * pricePerSquareFoot + (2.25 * televisions) + (5.50 * computers));
return charge;
}
public double purchaseTelevision( int quantity, double price)
{
double cost = 0.0;
if( quantity > televisions)
{
JOptionPane.showMessageDialog(null, "Television Quantity Unavailable");
price = 0.0;
}
else
{
cost = price * quantity;
televisions = televisions - quantity;
}
return cost;
}
public double purchaseComputer( int quantity, double price)
{
double cost = 0.0;
if( quantity > computers)
{
JOptionPane.showMessageDialog(null, "Computer Quantity Unavailable");
price = 0.0;
}
else
{
cost = price * quantity;
computers = computers - quantity;
}
return cost;
}
}
class Address{
private street = "123 Lame Street";
public getStreet(){
return street;
}
}
class Warehouse{
Address address = new Address(); // create an instance; not just declare
public void shipping(){
shipTo(address.getStreet()); // Here's how to "communicate"
}
}
You are on correct way. Your code is working. Because ToString is method of Object class that you overwrite in your class. http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html
Are you not getting correct result ?

Cant find Symbol error

The compiler gives me an error message saying it can't find movies[x].getTitle() and movies[x].getYear. I've been wondering if it's a problem with going through the interface to get to the classes
Here is the error:
MathewBorumP5.java:68: error: cannot find symbol
System.out.printf("%-26s%-6s%-10s%-9s%-11s\n", movies[x]
.getTitle(),
^
symbol: method getTitle()
location: interface Profitable
MathewBorumP5.java:69: error: cannot find symbol
movies[x].getYear(), movies[x].calcRevenue(),
^
symbol: method getYear()
location: interface Profitable
2 errors
Here is my client class:
import java.util.Scanner;
public class MathewBorumP5 {
public static void main(String[] args) {
int choice;
boolean restart = true;
Scanner input = new Scanner(System.in);
Profitable[] movies = new Profitable[6];
movies[0] = new Animated("Beauty and the Beast", "Gary Trousdale", 1991,
10.0, 5.0, 2.0);
movies[1] = new Animated("Peter Pan", "Clyde Geronimi", 1953, 2.0, 1.2,
.5);
movies[2] = new Documentary("Planet Earth", "Alastair Fothergill", 2006,
10, 20, 5);
movies[3] = new Documentary("Drain the Ocean", "Steve Nichols", 2009, 9,
2,3);
movies[4] = new Drama("The Shawshank Redemption", "Frank Darabont",
1994, 89, 7, 2);
movies[5] = new Drama("The Godfather", "Francis Coppola", 1972, 10, 3,
5);
do {
menu();
System.out.print("Enter a number from 1 - 5: ");
choice = input.nextInt();
System.out.print("\n");
switch(choice) {
case 1:
item1(movies);
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
restart = false;
break;
default:
System.out.print("You didn't enter a number between 1"
+ " and 5.\n");
break;
}
} while(restart == true);
}
public static void menu() {
System.out.print("Warren Moore Movie Menu\n");
System.out.print("1. Show the list of movies in the array\n");
System.out.print("2. Display the total number of movies and the total" +
" revenues\n");
System.out.print("3. Search movie by title\n");
System.out.print("4. Display movies sorted by profit in decreasing" +
" order\n");
System.out.print("5. Exit\n");
}
public static void item1(Profitable[] movies) {
double revenue;
System.out.printf("%-26s%-6s%-10s%-9s%-11s\n", "Title", "Year",
"Revenue", "Profit", "Category");
for(int x = 0; x <= 6; x++) {
revenue = movies[x].calcRevenue();
System.out.printf("%-26s%-6s%-10s%-9s%-11s\n", movies[x].getTitle(),
movies[x].getYear(), movies[x].calcRevenue(),
movies[x].calcProfit(revenue), movies[x].category());
}
}
}
Here is my superclass:
public class Movie implements Profitable {
protected String title;
protected String director;
protected int year;
protected double productionCost;
private int totalMovies = 0;
public Movie() {
totalMovies++;
}
public Movie(String newTitle, String newDirector, int newYear,
double newCost) {
totalMovies++;
title = newTitle;
director = newDirector;
year = newYear;
productionCost = newCost;
}
public int getTotalMovies() {
return totalMovies;
}
public String getTitle() {
return title;
}
public void setTitle(String newTitle) {
this.title = title;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public double getProductionCost() {
return productionCost;
}
public void setProductionCost(double productionCost) {
this.productionCost = productionCost;
}
public String toString() {
return "";
}
}
Here are my separate classes.
public class Animated extends Movie implements Profitable {
private double rate;
private double income;
public Animated() {
super();
}
public Animated(String title, String director, int year, double cost,
double rate, double income) {
super(title, director, year, cost);
this.rate = rate;
this.income = income;
}
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
public double getIncome() {
return income;
}
public void setIncome(double income) {
this.income = income;
}
public String category() {
return "Animated";
}
public double calcRevenue() {
return (income * rate);
}
public double calcProfit(double revenue) {
return (revenue - super.productionCost);
}
public String toString() {
return (super.toString() + "");
}
}
Number 2
public class Documentary extends Movie implements Profitable {
private int distributors;
private double premium;
public Documentary() {
super();
}
public Documentary(String title, String director, int year, double cost,
int distributors, double premium) {
super(title, director, year, cost);
this.distributors = distributors;
this.premium = premium;
}
public int getDistributors() {
return distributors;
}
public void setDistributors(int distributors) {
this.distributors = distributors;
}
public double getPremium() {
return premium;
}
public void setPremium(double premium) {
this.premium = premium;
}
public String category() {
return "Documentary";
}
public double calcRevenue() {
return (distributors * premium);
}
public double calcProfit(double revenue) {
return (revenue - super.productionCost);
}
public String toString() {
return (super.toString() + "");
}
}
Number 3
public class Drama extends Movie implements Profitable {
private int tickets;
private double avgPrice;
public Drama() {
super();
}
public Drama(String title, String director, int year, double cost,
int tickets, double avgPrice) {
super(title, director, year, cost);
this.tickets = tickets;
this.avgPrice = avgPrice;
}
public int getTickets() {
return tickets;
}
public void setTickets(int tickets) {
this.tickets = tickets;
}
public String category() {
return "Drama";
}
public double calcRevenue() {
return (tickets * avgPrice);
}
public double calcProfit(double revenue) {
return (revenue - super.productionCost);
}
public String toString() {
return (super.toString() + "");
}
}
And finally my interface.
public interface Profitable {
public abstract String category();
public abstract double calcRevenue();
public abstract double calcProfit(double revenue);
}
The Profitable interface doesn't have the methods that you're trying to call, and so the compiler is correct to complain about this to you. The array variable doesn't know what type of object each array item might hold, and in fact one could hold one type of item only to have it changed later, so it makes sense for the compiler to behave this way. A kludge would be to test each item held by the array to see what type it actually is, say by using instanceof, but this is a very fragile solution and is not recommended. Safest is to only call Profitable methods on Profitable array items and to try to use the magic of polymorphism to allow each object to do different behaviors for the same method call.
Note that if all of the items held by the array will always be Movie or Movie child items, then by all means use an array of Movie rather than an array of Profitable.
You are correct, the issue is with your Profitable interface.
When you create the array item(Profitable[] movies), this means that only the methods defined in this interface will be available to you.
An array of Movie objects is probably what you are after here. All of those objects appear extend Movie and implement Profitable, so you will able to access everything this way.

Categories