Cant find Symbol error - java

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.

Related

How to use polymorphism to access a method inside a subclass that is not defined in the super class using a reference variable of a superclass

If i have 2 classes the first one is BasicHamburger
public class BasicHamburger {
private String breadRollType;
private String meat;
private boolean lettuce;
private boolean tomato;
private boolean carrot;
private boolean cheese;
private int numberOfAdditions;
private int price;
public BasicHamburger(String breadRollType , String meat ,int price){
this.breadRollType = breadRollType;
this.meat = meat;
this.price = price;
lettuce = false;
tomato = false;
carrot = false;
cheese = false;
numberOfAdditions = 0;
}
public void addLettuce(){
lettuce = true;
incrementNumberOfAdditions();
}
public void addTomato(){
tomato = true;
incrementNumberOfAdditions();
}
public void addCarrot(){
carrot = true;
incrementNumberOfAdditions();
}
public void addCheese(){
cheese = true;
incrementNumberOfAdditions();
}
public int getNumberOfAdditions(){
return numberOfAdditions;
}
protected int incrementNumberOfAdditions(){
return ++numberOfAdditions;
}
public boolean isLettuce() {
return lettuce;
}
public boolean isTomato() {
return tomato;
}
public boolean isCarrot() {
return carrot;
}
public boolean isCheese() {
return cheese;
}
public int getBasicHamburgerPrice(){
return price;
}
public int getLettucePrice(){
return 20;
}
public int getTomatoPrice(){
return 15;
}
public int getCheesePrice(){
return 40;
}
public int getCarrotPrice(){
return 10;
}
public int getTotalBasicHamburgerPrice(){
if(isCarrot()){
price = price + 10;
}
if(isCheese()){
price = price + 40;
}
if(isTomato()){
price = price + 15;
}
if(isLettuce()){
price = price + 20;
}
return price;
}
public void displayBurgerDetailsWithPrices(){
if(isCarrot()){
System.out.println("Carrot addition = "+getCarrotPrice());
}
if(isCheese()){
System.out.println("Cheese addition = "+getCheesePrice());
}
if(isTomato()){
System.out.println("Tomato addition = "+getTomatoPrice());
}
if(isLettuce()){
System.out.println("Lettuce addition = "+getLettucePrice());
}
System.out.println("Basic Hamburger Total Price Without Additions = "+getBasicHamburgerPrice());
System.out.println("Basic Hamburger Total Price After Additions= "+getTotalBasicHamburgerPrice());
}
}
the second class is HealthyBurger
public class HealthyBurger extends BasicHamburger{
private boolean onion;
private boolean bacon;
public HealthyBurger(){
super("Brown Rye ","Mutton",30);
onion = false;
bacon = false;
}
public boolean isOnion() {
return onion;
}
public boolean isBacon() {
return bacon;
}
public void addOnion(){
onion = true;
incrementNumberOfAdditions();
}
public void addBacon(){
bacon = true;
incrementNumberOfAdditions();
}
public int getOnionPrice(){
return 15;
}
public int getBaconPrice(){
return 20;
}
#Override
public int getTotalBasicHamburgerPrice() {
int newPrice = super.getTotalBasicHamburgerPrice();
if(isBacon()){
newPrice += 20;
}
if(isOnion()){
newPrice +=15;
}
return newPrice;
}
#Override
public void displayBurgerDetailsWithPrices() {
if(isCarrot()){
System.out.println("Carrot addition = "+getCarrotPrice());
}
if(isCheese()){
System.out.println("Cheese addition = "+getCheesePrice());
}
if(isTomato()){
System.out.println("Tomato addition = "+getTomatoPrice());
}
if(isLettuce()){
System.out.println("Lettuce addition = "+getLettucePrice());
}
if(isOnion()){
System.out.println("Onion addition = "+getOnionPrice());
}
if(isBacon()){
System.out.println("Bacon addition = "+getBaconPrice());
}
System.out.println("Healthy Hamburger Total Price Without Additions = "+getBasicHamburgerPrice());
System.out.println("Healthy Hamburger Total Price After Additions= "+getTotalBasicHamburgerPrice());
}
}
in the main i have written this code
public class Main {
public static void DisplayBurger(BasicHamburger burger){
burger.displayBurgerDetailsWithPrices();
}
public static void main(String[] args) {
BasicHamburger ham1 = new BasicHamburger("x","beef",20);
ham1.addCarrot();
ham1.addCheese();
ham1.addLettuce();
ham1.addTomato();
HealthyBurger ham2 = new HealthyBurger();
ham2.addOnion();
ham2.addBacon();
BasicHamburger test = ham2;
DisplayBurger(test);
}
}
My confusion is the test variable can access displayBurgerDetailsWithPrices() function inside HealthyBurger class and can call the isOnion which is inside that function. Whereas if i decided to write that code inside the main i can not access the isOnion() function.
BasicHamburger newBurger = new HealthyBurger();
newBurger.isOnion();
To make the question clear and right to the point , why accessing a function inside a subclass through a overriden function is possible whereas accessing that function directly is not possible when using a variable of the superclass?
BasicHamburger newBurger = new HealthyBurger();
boolean onion = false;
if(newBurger instanceof HealthyBurger)
onion = ((HealthyBurger).isOnion());
To make the question clear and right to the point, why accessing a function inside a subclass through an overridden function is possible whereas accessing that function directly is not possible when using a variable of the superclass?
It calles Polymophism. The object reference BasicHamburger newBurger refers to the instance of class BasicHamburger or any of its children. It means that by default you have access only to the methods declared in BasicHamburger or any of its parent. If you want to call the children's method, you have to cast this reference to the required type.
I would redesign your code, because in general case if you use casting, then it looks like a design problem (repeat: in general; sometimes it really needed).
public abstract class Burger {
protected final String breadRollType;
protected final String meat;
protected final int basePrice;
protected final Set<Ingredient> ingredients;
protected Burger(String breadRollType, String meat, int basePrice, Set<Ingredient> ingredients) {
this.breadRollType = breadRollType;
this.meat = meat;
this.basePrice = basePrice;
this.ingredients = ingredients == null || ingredients.isEmpty() ? Set.of() : Set.copyOf(ingredients);
}
public final int getBasePrice() {
return basePrice;
}
protected int getIngredientsPrice() {
return ingredients.stream()
.map(Ingredient::getPrice)
.mapToInt(i -> i)
.sum();
}
public int getTotalPrice() {
return basePrice + getIngredientsPrice();
}
public final int getTotalIngredients() {
return ingredients.size();
}
public final boolean hasIngredient(Ingredient ingredient) {
return ingredient != null && ingredients.contains(ingredient);
}
public void printDetailsWithPrices() {
System.out.println(breadRollType + ' ' + meat);
System.out.println("----");
System.out.println("Basic price: " + basePrice);
System.out.println("Ingredients price: " + getIngredientsPrice());
ingredients.forEach(ingredient -> System.out.format("-> %s price: %d\n",
ingredient.getTitle(), ingredient.getPrice()));
System.out.println("Total price: " + getTotalPrice());
}
protected interface Ingredient {
String getTitle();
int getPrice();
}
}
public class HealthyBurger extends Burger {
public HealthyBurger(String breadRollType, String meat, int basePrice, Set<Burger.Ingredient> ingredients) {
super(breadRollType, meat, basePrice, ingredients);
}
public enum Ingredient implements Burger.Ingredient {
ONION("Onion", 15),
BACON("Bacon", 20);
private final String title;
private final int price;
Ingredient(String title, int price) {
this.title = title;
this.price = price;
}
#Override
public String getTitle() {
return title;
}
#Override
public int getPrice() {
return price;
}
}
}
public class PopularBurger extends Burger {
protected PopularBurger(String breadRollType, String meat, int basePrice, Set<Burger.Ingredient> ingredients) {
super(breadRollType, meat, basePrice, ingredients);
}
public enum Ingredient implements Burger.Ingredient {
LETTUCE("Lettuce", 20),
TOMATO("Tomato", 25),
CARROT("Carrot", 10),
CHEESE("Cheese", 40);
private final String title;
private final int price;
Ingredient(String title, int price) {
this.title = title;
this.price = price;
}
#Override
public String getTitle() {
return title;
}
#Override
public int getPrice() {
return price;
}
}
}
public static void main(String... args) {
PopularBurger popularBurger = new PopularBurger("x", "beef", 20,
Set.of(PopularBurger.Ingredient.CARROT,
PopularBurger.Ingredient.CHEESE,
PopularBurger.Ingredient.LETTUCE,
PopularBurger.Ingredient.TOMATO));
HealthyBurger healthyBurger = new HealthyBurger("Brown Rye", "Mutton", 30,
Set.of(HealthyBurger.Ingredient.ONION,
HealthyBurger.Ingredient.BACON));
PopularBurger one = popularBurger;
one.printDetailsWithPrices();
System.out.println();
HealthyBurger two = healthyBurger;
two.printDetailsWithPrices();
System.out.println();
boolean withOnion = two.hasIngredient(HealthyBurger.Ingredient.ONION);
System.out.println(withOnion);
}
x beef
----
Basic price: 20
Ingredients price: 95
-> Cheese price: 40
-> Carrot price: 10
-> Lettuce price: 20
-> Tomato price: 25
Total price: 115
Brown Rye Mutton
----
Basic price: 30
Ingredients price: 35
-> Onion price: 15
-> Bacon price: 20
Total price: 65
true

How to reset the getters and setters of a constructor

in my recent uni work ive been given a task which i believe is to reassign values that have been set by getters and setters. The exact question is
" Edit the product’s main information that shares among all class such as ID,
Description, etc"
My attempt at this question is as followed.
public void editProductInformation() { //Standard level task 2 method 3
this.ID = 456890;
this.description = "Eggs";
this.recommendedUnitPrice = 10;
this.Unit = 6;
this.weight = 750;
}
}
this is also the code for the rest of the class
public class Product {
Scanner input = new Scanner(System.in);
protected int ID;
protected String description;
protected double recommendedUnitPrice;
protected double actualPrice;
protected int Unit = 1;
protected double weight;
protected LocalDate expiaryDate;
protected LocalDate expireDate;
public Product(int ID, String description, double recommendedUnitPrice, int unit, double weight, LocalDate expiarayDate) {
this.ID = ID;
this.description = description;
this.recommendedUnitPrice = recommendedUnitPrice;
this.Unit = unit;
this.weight = weight;
this.expiaryDate = expiarayDate;
}
public int getID() {
return this.ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getDescription() {
return this.description;
}
public void setDescripption(String description) {
this.description = description;
}
public double getRecommendedUnitPrice() {
return this.recommendedUnitPrice;
}
public void setRecommendedUnitPrice(double recommendedUnitPrice) {
this.recommendedUnitPrice = recommendedUnitPrice;
}
public int getUnit() {
return this.Unit;
}
public void setUnit(int unit) {
this.Unit = unit;
}
public double getWeight() {
return this.weight;
}
public void setWeight(double Weight) {
this.weight = Weight;
}
public LocalDate getExpiaryDate() {
return expiaryDate;
}
public void setExpiaryDate(LocalDate expiaryDate) {
this.expiaryDate = expiaryDate;
}
public void setPrice() {
System.out.println("Enter the price: ");
this.actualPrice = input.nextDouble();
}
public void setExpireDate() {
System.out.println("Enter the given date: ");
int day = input.nextInt();
int month = input.nextInt();
int year = input.nextInt();
LocalDate date = LocalDate.of(day, month, year);
this.expireDate = date;
}
public void comparePrice() { // Standard level task 2 method 1
if (recommendedUnitPrice == actualPrice) {
System.out.println("Price is equal");
} else if (recommendedUnitPrice < actualPrice) {
System.out.println("Price is less");
} else if (recommendedUnitPrice > actualPrice) {
System.out.println("Price is more");
}
}
public void verifyExpireProduct() { //Standard level task 2 method 2
if(expireDate == expiaryDate) {
System.out.println("Product is expired");
}
else System.out.println("Product is not expired");
}
I understand this question might not be explained well enough so i understand if people wish to downvote it. Any insight or help is much appreciated!
You can make an object of this class and then by using setter function defined in class you can set the value .
Product p1 = new Product();
p1.setId(5);
//This will set the Id to 5

How do I fix "cannot find symbol" error?

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).

Array sorting printing and summing

What would be the simplest method to print this array broken down into each mobile phone as a product number, name department etc, and then re print the same information sorted by product name. I have tried a couple different methods and am already passed the turn in date for the assignment but still need to figure it out for upcoming assignment this weekend. When I try to implement the comparator on MobilePhone class it forces me to make it abstract or use #override but I can't figure out where or what to override to make it work because the abstract class causes a multitude of other problems.
package InventoryPro2;
import java.util.*;
class MobilePhone {
private double productNumber; // Variables
private String name;
private String department;
private double unitsInStock;
private double unitPrice;
public MobilePhone() {
this(0.0, "", "", 0.0, 0.0);
}
public MobilePhone(double productNumber, String name, String department,
double unitsInStock, double unitPrice) { //assign variables
this.productNumber = productNumber;
this.name = name;
this.department = department;
this.unitsInStock = unitsInStock;
this.unitPrice = unitPrice;
}
public double getproductNumber() { // retrieve values
return productNumber;
}
public String getname() {
return name;
}
public String getdepartment() {
return department;
}
public double getunitPrice() {
return unitPrice;
}
public double getunitsInStock() {
return unitsInStock;
}
public void setproductNumber(double productNumber) {
this.productNumber = productNumber;
}
public void setname(String name) {
this.name = name;
}
public void setdepartment(String department) {
this.department = department;
}
public void setunitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public void setunitsInStock(double unitsInStock) {
this.unitsInStock = unitsInStock;
}
public double gettotalInv() {
return getunitPrice() * getunitsInStock();
}
}
public class InventoryPro2 {
MobilePhone mobilephone = new MobilePhone();
public static void main(String args[]) {
System.out.println("Mobile Phone Inventory Program");
System.out.println();//skips a line
MobilePhone[] phones = new MobilePhone[5];
phones[0] = new MobilePhone();
phones[0].setproductNumber(1);
phones[0].setname("Motorola");
phones[0].setdepartment("Electronics");
phones[0].setunitPrice(150.10);
phones[0].setunitsInStock(98);
phones[1] = new MobilePhone();
phones[1].setproductNumber(2);
phones[1].setname("Samsung");
phones[1].setdepartment("Electronics");
phones[1].setunitPrice(199.99);
phones[1].setunitsInStock(650);
phones[2] = new MobilePhone();
phones[2].setproductNumber(3);
phones[2].setname("Nokia");
phones[2].setdepartment("Electronics");
phones[2].setunitPrice(200.25);
phones[2].setunitsInStock(125);
phones[3] = new MobilePhone();
phones[3].setproductNumber(4);
phones[3].setname("LG");
phones[3].setdepartment("Electronics");
phones[3].setunitPrice(100.05);
phones[3].setunitsInStock(200);
phones[4] = new MobilePhone();
phones[4].setproductNumber(5);
phones[4].setname("IPhone");
phones[4].setdepartment("Electronics");
phones[4].setunitPrice(299.99);
phones[4].setunitsInStock(150);
System.out.println("Order of inventory before sorting:");
System.out.println();
}
}
(Also, what is the best way to take just one piece of information out of each part of the array such as the totalInv and total all of those numbers to print?) Do I have unnecessary code here or have I done everything right thus far? I have to say that learning this coding language in an online format has not been a very enjoyable experience thus far..
Here is how to sort by name
import java.util.Arrays;
import java.util.Comparator;
public class AppInventoryPro2 {
public static void main(String... args) {
System.out.println("Mobile Phone Inventory Program");
System.out.println();// skips a line
MobilePhone[] phones = new MobilePhone[5];
phones[0] = new MobilePhone();
phones[0].setproductNumber(1);
phones[0].setname("Motorola");
phones[0].setdepartment("Electronics");
phones[0].setunitPrice(150.10);
phones[0].setunitsInStock(98);
phones[1] = new MobilePhone();
phones[1].setproductNumber(2);
phones[1].setname("Samsung");
phones[1].setdepartment("Electronics");
phones[1].setunitPrice(199.99);
phones[1].setunitsInStock(650);
phones[2] = new MobilePhone();
phones[2].setproductNumber(3);
phones[2].setname("Nokia");
phones[2].setdepartment("Electronics");
phones[2].setunitPrice(200.25);
phones[2].setunitsInStock(125);
phones[3] = new MobilePhone();
phones[3].setproductNumber(4);
phones[3].setname("LG");
phones[3].setdepartment("Electronics");
phones[3].setunitPrice(100.05);
phones[3].setunitsInStock(200);
phones[4] = new MobilePhone();
phones[4].setproductNumber(5);
phones[4].setname("IPhone");
phones[4].setdepartment("Electronics");
phones[4].setunitPrice(299.99);
phones[4].setunitsInStock(150);
System.out.println("Order of inventory before sorting:");
System.out.println(Arrays.toString(phones));
Arrays.sort(phones, new Comparator<MobilePhone>() {
#Override
public int compare(MobilePhone mp1, MobilePhone mp2) {
return mp1.getname().compareTo(mp2.getname());
}
});
System.out.println("Order of inventory after sorting by name:");
System.out.println(Arrays.toString(phones));
}
}
class MobilePhone {
private double productNumber; // Variables
private String name;
private String department;
private double unitsInStock;
private double unitPrice;
public MobilePhone() {
this(0.0, "", "", 0.0, 0.0);
}
public MobilePhone(double productNumber, String name, String department,
double unitsInStock, double unitPrice) { // assign variables
this.productNumber = productNumber;
this.name = name;
this.department = department;
this.unitsInStock = unitsInStock;
this.unitPrice = unitPrice;
}
public double getproductNumber() { // retrieve values
return productNumber;
}
public String getname() {
return name;
}
public String getdepartment() {
return department;
}
public double getunitPrice() {
return unitPrice;
}
public double getunitsInStock() {
return unitsInStock;
}
public void setproductNumber(double productNumber) {
this.productNumber = productNumber;
}
public void setname(String name) {
this.name = name;
}
public void setdepartment(String department) {
this.department = department;
}
public void setunitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public void setunitsInStock(double unitsInStock) {
this.unitsInStock = unitsInStock;
}
public double gettotalInv() {
return getunitPrice() * getunitsInStock();
}
#Override
public String toString() {
return "MobilePhone [productNumber=" + productNumber + ", name=" + name
+ ", department=" + department + ", unitsInStock="
+ unitsInStock + ", unitPrice=" + unitPrice + "]";
}
}
1 - To print content of MobilePhone class: Override default toString method like this:
#Override
public String toString() {
return "MobilePhone [productNumber=" + productNumber +
", name=" + name + ']'; // add more info if needed
}
2 - To allow sorting by name: Have MobilePhone class implement Comparable interface like
this:
class MobilePhone implements Comparable {
...
#Override
public int compareTo(Object o) {
MobilePhone m = (MobilePhone) o;
return (this.name.compareTo(o.name));
}
}
EDIT: To print your array of MobilePhone object you can do:
System.out.printf("Phones: %s%n", Arrays.toString(phones));

How to make an array of child objects

I have an assignment from my professor and I can't figure out how to properly create an array of objects. None of the classes but the Client class can be changed; the interface can't be changed either. I'm supposed to be able to create an array of objects from several subclasses and be able to access all of the methods.
Here is my error report:
MathewBorumP5.java:68: error: cannot find symbol
revenue = movies[x].calcRevenue();
^
symbol: method calcRevenue()
location: class Movie
MathewBorumP5.java:70: error: cannot find symbol
movies[x].getYear(), movies[x].calcRevenue(),
^
symbol: method calcRevenue()
location: class Movie
MathewBorumP5.java:71: error: cannot find symbol
movies[x].calcProfit(revenue), movies[x].categor
y());
^
symbol: method calcProfit(double)
location: class Movie
MathewBorumP5.java:71: error: cannot find symbol
movies[x].calcProfit(revenue), movies[x].categor
y());
^
symbol: method category()
location: class Movie
MathewBorumP5.java:78: error: cannot find symbol
totalRevenue = totalRevenue + movies[x].calcRevenue();
^
symbol: method calcRevenue()
location: class Movie
MathewBorumP5.java:81: error: cannot find symbol
"%.3f million dollars.", Movie[0].getTotalMovies(), tota
lRevenue);
^
symbol: variable Movie
location: class MathewBorumP5
6 errors
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);
Movie[] movies = new Movie[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:
item2(movies);
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(Movie[] 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());
}
}
public static void item2(Movie[] movies) {
double totalRevenue;
for(int x = movies[0].getTotalMovies(); x > 0; x--) {
totalRevenue = totalRevenue + movies[x].calcRevenue();
}
printf("The total number of moves is %d, and their total revenue is" +
"%.3f million dollars.", Movie[0].getTotalMovies(), totalRevenue);
}
}
My Superclass:
public class Movie {
protected String title;
protected String director;
protected int year;
protected double productionCost;
private static 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 "";
}
}
Class template(all my classes are basically the same):
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() + "");
}
}
My interface:
public interface Profitable {
public abstract String category();
public abstract double calcRevenue();
public abstract double calcProfit(double revenue);
}
You need to add appropriate cast and test using instanceof.
revenue = movies[x].calcRevenue();
must be replaced by
if (movies[x] instanceof Profitable) {
revenue = ((Profitable)movies[x]).calcRevenue();
} else {
// decide what to do if movie if not profitable that is to say does not have the calcRevenue method
}

Categories