How to make an array of child objects - java

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
}

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

Visual Studio Code Java: Cannot find symbol (class name)?

So I have a relatively simple program using two classes. When I compile the class I want to run I get an error saying cannot find symbol "Fighter" which is the name of my class that I am using the objects from. Both classes are in the same package. NOTE It works fine in NetBeans but I prefer to use VSC.
Here is my code.
Class I am running:
package project;
import java.util.ArrayList;
import java.util.Scanner;
public class Division
{
public static Scanner scanner = new Scanner(System.in);
public static void main(String args[])
{
ArrayList<Fighter> fighters = new ArrayList();
fighters.add(new Fighter("Conor McGregor", 29, "Ireland", 21, 3));
fighters.add(new Fighter("Gunnar Nelson", 28, "Iceland", 16, 3));
fighters.add(new Fighter("Stipe Miocic", 33, "USA", 17, 2));
fighters.add(new Fighter("Cody Garbrandt", 26, "USA", 11, 0));
fighters.add(new Fighter("Demetrious Johnson", 30, "USA", 27, 2));
fighters.add(new Fighter("Jose Aldo", 31, "Brazil", 26, 3));
fighters.add(new Fighter("George St Pierre", 40, "Canada", 25, 2));
fighters.add(new Fighter("Fabricio Werdum", 40, "Brazil", 22, 7));
fighters.add(new Fighter("Michael Bisping", 39, "United Kingdom", 30, 7));
displayAllFighters(fighters);
}
//Adds fighter to ArrayList
public static void addFighter(ArrayList<Fighter> fighters)
{
System.out.print("Please enter fighters name: \t");
String name = scanner.nextLine();
System.out.print("\nPlease enter fighters age: \t");
int age = scanner.nextInt();
scanner.nextLine();
System.out.print("\nPlease enter fighters country: \t");
String country = scanner.nextLine();
System.out.print("\nPlease enter amount of wins: \t");
int wins = scanner.nextInt();
System.out.print("\nPlease enter amount of losses: \t");
int losses = scanner.nextInt();
fighters.add(new Fighter(name, age, country, wins, losses));
System.out.println("Fighter Added!");
}
//Removes a fighter from ArrayList
public static void removeFighter(ArrayList<Fighter> fighters)
{
System.out.print("Please enter the name of the fighter you wish to remove: \t");
String name = scanner.nextLine();
for (Fighter fighter : fighters)
{
if (fighter.getName() == name)
{
fighters.remove(fighter);
}
}
}
public static void displayAllFighters(ArrayList<Fighter> fighters)
{
for (Fighter fighter : fighters)
{
System.out.println(fighter);
System.out.println("==========================================");
}
}
public static int countWinPercentLowerThan(ArrayList<Fighter> fighters , int value)
{
int count = 0;
for (Fighter fighter : fighters)
{
if (fighter.getPercent() < value)
{
count++;
}
}
return count;
}
public static int countWinPercentGreaterThan(ArrayList<Fighter> fighters , int value)
{
int count = 0;
for (Fighter fighter : fighters)
{
if (fighter.getPercent() > value)
{
count++;
}
}
return count;
}
}
Class that isn't being recognized.
package project;
public class Fighter
{
private String name;
private int age;
private String country;
private int wins;
private int losses;
public Fighter(String name, int age, String country, int wins, int losses)
{
this.name = name;
this.age = age;
this.country = country;
this.wins = wins;
this.losses = losses;
}
public Fighter(String name)
{
this.name = name;
this.age = 0;
this.country = "TBA";
this.wins = 0;
this.losses = 0;
}
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return this.age;
}
public void setAge(int age)
{
this.age = age;
}
public String getCountry()
{
return this.country;
}
public void setCountry(String country)
{
this.country = country;
}
public int getWins()
{
return this.wins;
}
public void setWins(int wins)
{
this.wins = wins;
}
public int getLosses()
{
return this.losses;
}
public void setLosses(int losses)
{
this.losses = losses;
}
public String toString()
{
return "Fighter Name: " + this.name + ".\nFighter age: " + this.age + ".\nFighter nation: " + this.country + ".\nFighter wins: " + this.wins + ".\nFighter losses: " + this.losses + ".";
}
public void updateWin()
{
this.wins++;
}
public void updateLosses()
{
this.losses++;
}
public double getPercent()
{
int totalFights = this.wins + this.losses;
double percent = this.wins * 100/totalFights;
return percent;
}
}
Thank you in advanced!

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

java.util.Scanner; vs JOptionPane; [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Please I would like know How would I implement JOptionPane instead of import java.util.Scanner;
I also have 4 separate classes
If i implement JOptionPane will it clean up the code I would also like to know any changes anyone would make.
Employee.Class
import java.text.NumberFormat;
import java.util.Scanner;
public class Employee {
public static int numEmployees = 0;
protected String firstName;
protected String lastName;
protected char gender;
protected int dependents;
protected double annualSalary;
private NumberFormat nf = NumberFormat.getCurrencyInstance();
public Benefit benefit;
private static Scanner scan;
public Employee() {
firstName = "";
lastName = "";
gender = 'U';
dependents = 0;
annualSalary = 40000;
benefit = new Benefit();
numEmployees++;
}
public Employee(String first, String last, char gen, int dep, Benefit benefit1) {
this.firstName = first;
this.lastName = last;
this.gender = gen;
this.annualSalary = 40000;
this.dependents = dep;
this.benefit = benefit1;
numEmployees++;
}
public double calculatePay1() {
return annualSalary / 52;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("First Name: ").append(firstName).append("\n");
sb.append("Last Name: ").append(lastName).append("\n");
sb.append("Gender: ").append(gender).append("\n");
sb.append("Dependents: ").append(dependents).append("\n");
sb.append("Annual Salary: ").append(nf.format(getAnnualSalary())).append("\n");
sb.append("Weekly Pay: ").append(nf.format(calculatePay1())).append("\n");
sb.append(benefit.toString());
return sb.toString();
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public <Gender> void setGender(char gender) {
this.gender = gender;
}
public <Gender> char getGender() {
return gender;
}
public void setDependents(int dependents) {
this.dependents = dependents;
}
public void setDependents(String dependents) {
this.dependents = Integer.parseInt(dependents);
}
public int getDependents() {
return dependents;
}
public void setAnnualSalary(double annualSalary) {
this.annualSalary = annualSalary;
}
public void setAnnualSalary(String annualSalary) {
this.annualSalary = Double.parseDouble(annualSalary);
}
public double getAnnualSalary() {
return annualSalary;
}
public double calculatePay() {
return annualSalary / 52;
}
public double getAnnualSalary1() {
return annualSalary;
}
public static void displayDivider(String outputTitle) {
System.out.println(">>>>>>>>>>>>>>> " + outputTitle + " <<<<<<<<<<<<<<<");
}
public static String getInput(String inputType) {
System.out.println("Enter the " + inputType + ": ");
scan = new Scanner(System.in);
String input = scan.next();
return input;
}
public static int getNumEmployees() {
return numEmployees;
}
public static void main(String[] args) {
displayDivider("New Employee Information");
Benefit benefit = new Benefit();
Employee employee = new Employee("George", "Anderson", 'M', 5, benefit);
System.out.println(employee.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Hourly Temp Employee Information");
Hourly hourly = new Hourly("Mary", "Nola", 'F', 5, 14, 45, "temp");
System.out.println(hourly.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Hourly Full Time Employee Information");
Hourly hourly1 = new Hourly("Mary", "Nola", 'F', 5, 18, 42, "full time");
System.out.println(hourly1.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Hourly Part Time Employee Information");
Hourly hourly11 = new Hourly("Mary", "Nola", 'F', 5, 18, 20, "part time");
System.out.println(hourly11.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Salaried Revised Employee Information");
Benefit benefit1 = new Benefit("None", 500, 3);
Salaried salaried = new Salaried("Frank", "Lucus", 'M', 5, 150000, benefit1, 3);
System.out.println(salaried.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Salaried Employee Information");
Benefit benefit11 = new Benefit("None", 500, 3);
Salaried salaried1 = new Salaried("Frank", "Lucus", 'M', 5, 100000, benefit11, 2);
System.out.println(salaried1.toString());
System.out.println("Total employees: " + getNumEmployees());
}
}
SALARIED.CLASS
import java.util.Random;
import java.util.Scanner;
public class Salaried extends Employee {
private static final int MIN_MANAGEMENT_LEVEL = 0;
private static final int MAX_MANAGEMENT_LEVEL = 3;
private static final int BONUS_PERCENT = 10;
private int managementLevel;
private Scanner in;
public Salaried() {
super();
Random rand = new Random();
managementLevel = rand.nextInt(4) + 1;
if (managementLevel == 0) {
System.out.println("Not Valid");
}
//numEmployees++;
}
private boolean validManagementLevel(int level) {
return (MIN_MANAGEMENT_LEVEL <= level && level <= MAX_MANAGEMENT_LEVEL);
}
public Salaried(String fname, String lname, char gen, int dep,
double sal, Benefit ben, int manLevel)
{
super.firstName = fname;
super.lastName = lname;
super.gender = gen;
super.dependents = dep;
super.annualSalary = sal;
super.benefit = ben;
while (true) {
if (!validManagementLevel(manLevel)) {
System.out.print("Invalid management level, please enter
another management level value in range [0,3]: ");
manLevel = new Scanner(System.in).nextInt();
} else {
managementLevel = manLevel;
break;
}
}
//numEmployees++;
}
public Salaried(double sal, int manLevel) {
super.annualSalary = sal;
while (true) {
if (!validManagementLevel(manLevel)) {
System.out.print("Invalid management level, please enter another
management level value in range [0,3]: ");
in = new Scanner(System.in);
manLevel = in.nextInt();
} else {
managementLevel = manLevel;
break;
}
}
// numEmployees++;
}
#Override
public double calculatePay() {
double percentage = managementLevel * BONUS_PERCENT;
return (1 + percentage/100.0) * annualSalary / 52;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
sb.append("Management Level: ").append(managementLevel).append("\n");
return sb.toString();
}
}
Hourly.Class
import java.util.Scanner;
public class Hourly extends Employee {
private static final double MIN_WAGE = 10;
private static final double MAX_WAGE = 75;
private static final double MIN_HOURS = 0;
private static final double MAX_HOURS = 50;
private double wage;
private double hours;
private String category;
private Scanner in;
private Scanner in2;
private Scanner in3;
private Scanner in4;
public Hourly() {
super();
this.wage = 20;
this.hours= 30;
this.category = "full time";
annualSalary = wage * hours * 52;
}
public Hourly(double wage_, double hours_, String category_) {
while (true) {
if (!validWage(wage_)) {
System.out.print("Invalid wage: ");
in2 = new Scanner(System.in);
wage_ = in2.nextDouble();
} else {
this.wage = wage_;
break;
}
}
while (true) {
if (!validHour(hours_)) {
System.out.print("Invalid hours: ");
in = new Scanner(System.in);
hours_ = in.nextDouble();
} else {
this.hours = hours_;
break;
}
}
while (true) {
if (!validCategory(category_)) {
System.out.print("Invalid category, please enter another category value: ");
category_ = new Scanner(System.in).next();
} else {
this.category = category_;
break;
}
}
annualSalary = wage * hours * 52;
//numEmployees++;
}
public Hourly(String fname, String lname, char gen, int dep, double wage_,double hours_, String category_) {
super.firstName = fname;
super.lastName = lname;
super.gender = gen;
super.dependents = dep;
super.annualSalary = annualSalary;
super.benefit = benefit;
while (true) {
if (!validWage(wage_)) {
System.out.print("Invalid wage : ");
in3 = new Scanner(System.in);
wage_ = in3.nextDouble();
} else {
this.wage = wage_;
break;
}
}
while (true) {
if (!validHour(hours_)) {
System.out.print("Invalid hours : ");
hours_ = new Scanner(System.in).nextDouble();
} else {
this.hours = hours_;
break;
}
}
while (true) {
if (!validCategory(category_)) {
System.out.print("Invalid category, please enter another category value: ");
in4 = new Scanner(System.in);
category_ = in4.next();
} else {
this.category = category_;
break;
}
}
annualSalary = wage * hours * 52;
//numEmployees++;
}
private boolean validHour(double hour) {
return (MIN_HOURS <= hour && hour <= MAX_HOURS);
}
private boolean validWage(double wage) {
return (MIN_WAGE <= wage && wage <= MAX_WAGE);
}
private boolean validCategory(String category) {
String[] categories = {"temp", "part time", "full time"};
for (int i = 0; i < categories.length; i++)
if (category.equalsIgnoreCase(categories[i]))
return true;
return false;
}
public double calculatePay() {
return annualSalary / 52;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
sb.append("Wage: ").append(wage).append("\n");
sb.append("Hours: ").append(hours).append("\n");
sb.append("Category: ").append(category).append("\n");
return sb.toString();
}
}
Benefit.Class
public class Benefit {
private String healthInsurance;
private double lifeInsurance;
private int vacationDays;
public Benefit() {
healthInsurance = "Full";
lifeInsurance = 100;
vacationDays = 5;
}
public Benefit(String health, double life, int vacation) {
setHealthInsurance(health);
setLifeInsurance(life);
setVacation(vacation);
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Health Insurance: ").append(healthInsurance).append("\n");
sb.append("Life Insurance: ").append(lifeInsurance).append("\n");
sb.append("Vacation Days: ").append(vacationDays).append("\n");
return sb.toString();
}
public void setHealthInsurance(String healthInsurance) {
this.healthInsurance = healthInsurance;
}
public String getHealthInsurance() {
return healthInsurance;
}
public void setLifeInsurance(double lifeInsurance) {
this.lifeInsurance = lifeInsurance;
}
public double getLifeInsurance() {
return lifeInsurance;
}
public void setVacation(int vacation) {
this.vacationDays = vacation;
}
public int getVacation() {
return vacationDays;
}
public void displayBenefit() {
this.toString();
}
}
Start by taking a look at How to Make Dialogs...
What you basically want is to use JOptionPane.showInputDialog, which can be used to prompt the use for input...
Yes, there are a few flavours, but lets keep it simply and look at JOptionPane.showInputDialog(Object)
The JavaDocs tells us that...
message - the Object to display
Returns:user's input, or null meaning the user canceled the input
So, from that we could use something like...
String value = JOptionPane.showInputDialog("What is your name?");
if (value != null) {
System.out.println("Hello " + value);
} else {
System.out.println("Hello no name");
}
Which displays...
Now, if we take a look at your code, you could replace the use of scan with...
public static String getInput(String inputType) {
String input = JOptionPane.showInputDialog("Enter the " + inputType + ": ");
return input;
}
As an example...
Now, what I might recommend is creating a simple helper method which can be used to prompt the user in a single line of code, for example...
public class InputHelper {
public static String promptUser(String prompt) {
String input = JOptionPane.showInputDialog(prompt);
return input;
}
}
which might be used something like...
String value = InputHelper.promptUser("Please enter the hours worked");
hours_ = Double.parse(value);
And this is where it get's messy, as you will now need to valid the input of the user.
You could extend the idea of the InputHelper to do automatic conversions and re-prompt the user if the value was invalid...as an idea
It is much easier than you think, if you try. Get used to reading the Java API.
http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html
Even has examples.
String input;
JOptionPane jop=new JOptionPane();
input=jop.showInputDialog("Question i want to ask");
System.out.println(input);

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