I wrote a small project named Sales Taxes on Intellij IDEA. To run the program, I included a main method. Now I need to write JUnit tests for the project. I do not have much experience about writing test classes. How can I turn my main method to Junit test class?
Here is the project that I constructed:
Basic sales tax is applicable at a rate of 10% on all goods, except books, food, and medical products that are exempt.
Import duty is an additional sales tax applicable on all imported goods at a rate of 5%, with no exemptions.
When I purchase items I receive a receipt which lists the name of all the items and their price (including tax), finishing
with the total cost of the items, and the total amounts of sales taxes paid. The rounding rules for sales tax are that for
a tax rate of n%, a shelf price of p contains (np/100 rounded up to the nearest 0.05) amount of sales tax.
Write an application that prints out the receipt details for these shopping baskets...
Product.java
/*
Definition of Product.java class
Fundamental object for the project.
It keeps all features of the product.
At description of the product, description of the input line for output line.
typeOfProduct: 0:other 1:food 2:book 3: medical products
*/
public class Product{
private int typeOfProduct=0;
private boolean imported=false;
private double price=0;
private double priceWithTaxes=0;
private double taxes=0;
private int quantity=0;
private String description="";
public Product(int quantity, int typeOfProduct, boolean imported, double price, String description)
{
this.quantity=quantity;
this.typeOfProduct = typeOfProduct;
this.imported = imported;
this.price = price;
this.description = description;
}
public void setTypeOfProduct(int typeOfProduct)
{
this.typeOfProduct = typeOfProduct;
}
public int getTypeOfProduct()
{
return typeOfProduct;
}
public void setImported(boolean imported)
{
this.imported = imported;
}
public boolean getImported()
{
return imported;
}
public void setPrice(double price)
{
this.price = price;
}
public double getPrice()
{
return price;
}
public void setTaxes(double taxes)
{
this.taxes = taxes;
}
public double getTaxes()
{
return taxes;
}
public void setPriceWithTaxes(double priceWithTaxes)
{
this.priceWithTaxes = priceWithTaxes;
}
public double getPriceWithTaxes()
{
return priceWithTaxes;
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
public int getQuantity()
{
return quantity;
}
public void setDescription(String description)
{
this.description = description;
}
public String getDescription()
{
return description;
}
}
TaxCalculator.java
/*
Definition of TaxCalculator.java class
At constructor a Product object is taken.
taxCalculate method; adds necessary taxes to price of product.
Tax rules:
1. if the product is imported, tax %5 of price
2. if the product is not food, book or medical goods, tax %10 of price
typeOfProduct: 0:food 1:book 2: medical products 3:other
*/
public class TaxCalculator {
private Product product=null;
public TaxCalculator(Product product)
{
this.product=product;
}
public void taxCalculate()
{
double price=product.getPrice();
double tax=0;
//check impoted or not
if(product.getImported())
{
tax+= price*5/100;
}
//check type of product
if(product.getTypeOfProduct()==3)
{
tax+= price/10;
}
product.setTaxes(Util.roundDouble(tax));
product.setPriceWithTaxes(Util.roundDouble(tax)+price);
}
}
Util.java
import java.text.DecimalFormat;
/*
Definition of Util.java class
It rounds and formats the price and taxes.
Round rules for sales taxes: rounded up to the nearest 0.05
Format: 0.00
*/
public class Util {
public static String round(double value)
{
double rounded = (double) Math.round(value * 100)/ 100;
DecimalFormat df=new DecimalFormat("0.00");
rounded = Double.valueOf(df.format(rounded));
return df.format(rounded).toString();
}
public static double roundDouble(double value)
{
double rounded = (double) Math.round(value * 20)/ 20;
if(rounded<value)
{
rounded = (double) Math.round((value+0.05) * 20)/ 20;
}
return rounded;
}
public static String roundTax(double value)
{
double rounded = (double) Math.round(value * 20)/ 20;
if(rounded<value)
{
rounded = (double) Math.round((value+0.05) * 20)/ 20;
}
DecimalFormat df=new DecimalFormat("0.00");
rounded = Double.valueOf(df.format(rounded));
return df.format(rounded).toString();
}
}
SalesManager.java
import java.util.ArrayList;
import java.util.StringTokenizer;
/*
Definition of SalesManager.java class
This class asks to taxes to TaxCalculator Class and creates Product objects.
*/
public class SalesManager {
private String [][] arTypeOfProduct = new String [][]{
{"CHOCOLATE", "CHOCOLATES", "BREAD", "BREADS", "WATER", "COLA", "EGG", "EGGS"},
{"BOOK", "BOOKS"},
{"PILL", "PILLS", "SYRUP", "SYRUPS"}
};
/*
* It takes all inputs as ArrayList, and returns output as ArrayList
* Difference between output and input arrayLists are Total price and Sales Takes.
*/
public ArrayList<String> inputs(ArrayList<String> items)
{
Product product=null;
double salesTaxes=0;
double total=0;
TaxCalculator tax=null;
ArrayList<String> output=new ArrayList<String>();
for(int i=0; i<items.size(); i++)
{
product= parse(items.get(i));
tax=new TaxCalculator(product);
tax.taxCalculate();
salesTaxes+=product.getTaxes();
total+=product.getPriceWithTaxes();
output.add(""+product.getDescription()+" "+Util.round(product.getPriceWithTaxes()));
}
output.add("Sales Taxes: "+Util.round(salesTaxes));
output.add("Total: "+Util.round(total));
return output;
}
/*
* The method takes all line and create product object.
* To create the object, it analyses all line.
* "1 chocolate bar at 0.85"
* First word is quantity
* Last word is price
* between those words, to analyse it checks all words
*/
public Product parse(String line)
{
Product product=null;
String productName="";
int typeOfProduct=0;
boolean imported=false;
double price=0;
int quantity=0;
String description="";
ArrayList<String> wordsOfInput = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(line, " ");
String tmpWord="";
while (st.hasMoreTokens())
{
tmpWord=st.nextToken();
wordsOfInput.add(tmpWord);
}
quantity=Integer.parseInt(wordsOfInput.get(0));
imported = searchImported(wordsOfInput);
typeOfProduct = searchTypeOfProduct(wordsOfInput);
price=Double.parseDouble(wordsOfInput.get(wordsOfInput.size()-1));
description=wordsOfInput.get(0);
for(int i=1; i<wordsOfInput.size()-2; i++)
{
description=description.concat(" ");
description=description.concat(wordsOfInput.get(i));
}
description=description.concat(":");
product=new Product(quantity, typeOfProduct, imported, price, description);
return product;
}
/*
* It checks all line to find "imported" word, and returns boolean as imported or not.
*/
public boolean searchImported(ArrayList<String> wordsOfInput)
{
boolean result =false;
for(int i=0; i<wordsOfInput.size(); i++)
{
if(wordsOfInput.get(i).equalsIgnoreCase("imported"))
{
return true;
}
}
return result;
}
//typeOfProduct: 0:food 1:book 2: medical goods 3:other
/*
* It checks all 2D array to find the typeOf product
* i=0 : Food
* i=1 : Book
* i=2 : Medical goods
*/
public int searchTypeOfProduct (ArrayList<String> line)
{
int result=3;
for(int k=1; k<line.size()-2; k++)
{
for(int i=0; i<arTypeOfProduct.length; i++)
{
for(int j=0; j<arTypeOfProduct[i].length; j++)
{
if(line.get(k).equalsIgnoreCase(arTypeOfProduct[i][j]))
{
return i;
}
}
}
}
return result;
}
}
SalesTaxes.java
import java.io.IOException;
import java.util.ArrayList;
public class SalesTaxes {
public static void main(String args[]) throws IOException
{
ArrayList<String> input = new ArrayList<String>();
ArrayList<String> output = new ArrayList<String>();
SalesManager sal = new SalesManager();
/*
* First input set
*/
System.out.println("First input Set");
System.out.println();
input = new ArrayList<String>();
input.add("1 book at 12.49");
input.add("1 music CD at 14.99");
input.add("1 chocolate bar at 0.85");
sal=new SalesManager();
output= sal.inputs(input);
for(int i=0; i<output.size(); i++)
{
System.out.println(output.get(i));
}
/*
* Second input set
*/
System.out.println();
System.out.println("Second input Set");
System.out.println();
input = new ArrayList<String>();
input.add("1 imported box of chocolates at 10.00");
input.add("1 imported bottle of perfume at 47.50");
sal=new SalesManager();
output= sal.inputs(input);
for(int i=0; i<output.size(); i++)
{
System.out.println(output.get(i));
}
/*
* Third input set
*/
System.out.println();
System.out.println("Third input Set");
System.out.println();
input = new ArrayList<String>();
input.add("1 imported bottle of perfume at 27.99");
input.add("1 bottle of perfume at 18.99");
input.add("1 packet of headache pills at 9.75");
input.add("1 box of imported chocolates at 11.25");
output= sal.inputs(input);
for(int i=0; i<output.size(); i++)
{
System.out.println(output.get(i));
}
}
}
I think that you can start with searching about how to write unit tests, maybe than you will not have this kind of question. The main point there is to test some piece of functionality. For example, in your case you should test taxCalculate method and check if in your product the tax was set correctly, probably you will need a getter for a product in this case.
Also, check this: how to write a unit test.
A "unit test" is for one class.
So I wouldn't start with the main method: that wouldn't give you "unit tests". That would give you an "integration test" (testing a bunch of your classes all at once).
So, for unit tests, I would start by writing a UtilTest class to test just your Util class. That has public methods that can easily be given different inputs and the results asserted. e.g. what do you get back if you give roundTax zero, or 21.0, etc.?
Related
I've still learning java so bear with me.
Building off previous work. So I have a abstract Stock class with class ETF and class Dividend that both extends Stock class. ETF and Dividend override a calculatePrice from Stock. In another StockManager class, I can take some input as stock name, stock price, and either a value for ETF or dividend. Previously I stored these inputs into a object array
Stock[] stk = new Stock[STOCKLIMIT]
Now since Stock is an abstract class I can't do that anymore. How do I store these values? or print them?
Along with that, in StockManager you can add, remove, print, or find total cost of the stocks.
Deleted some things that are unneeded
Just need some help for adding, printing, and total cost
StockManager class
public class StockManager
{
Scanner stdin = new Scanner(System.in);
final int STOCKLIMIT = 6;
int numberOfStocks = 0;
Stock[] stk = new Stock[STOCKLIMIT]; //before stock was abstract
String name;
Double namePrice;
int etfDividendVal;
public void run()
{
String command = stdin.next();
while (!command.equalsIgnoreCase("Q"))
{
if (command.equalsIgnoreCase("A"))
{
else
{
String commandTwo = stdin.next(); //either e for etf or d for dividend
if (commandTwo.equalsIgnoreCase("E"))
{
name = stdin.next();
namePrice = stdin.nextDouble();
etfDividendVal = stdin.nextInt();
//stk[numberOfStocks] = new Stock(name, namePrice); //object array when stock wasn't abstract
//store name, namePrice, and etfDividendVal somewhere now that stock is abstract
numberOfStocks++;
}
else if (commandTwo.equalsIgnoreCase("D"))
{
name = stdin.next();
namePrice = stdin.nextDouble();
etfDividendVal = stdin.nextInt();
//stk[numberOfStocks] = new Stock(name, namePrice);
//where to store name, namePrice, and etfDividendVal somewhere now that stock is abstract
Stock stk = new Dividend();
numberOfStocks++;
}
}
}
}
else if (command.equalsIgnoreCase("R")) //remove a stock
{
else
{
name = stdin.next();
namePrice = stdin.nextDouble();
for (int i = 0; i < numberOfStocks; i++)
{
if (stk[i].getTicker().equals(name))
{
for(int z = i; z < numberOfStocks; z++)
{
if (z + 1 == numberOfStocks)
stk[z] = null;
else
stk[z] = stk[z+1];
}
numberOfStocks--;
}
}
}
}
else if (command.equalsIgnoreCase("P"))
{
else
{
// print stock name, price, and etf/divident value
}
}
}
else if (command.equalsIgnoreCase("C"))
{
else
{
//print the total cost
}
}
}
}
}
Abstract Stock class
abstract public class Stock
{
protected String commandTwo;
protected String ticker;
protected Double price;
protected int etfDividendVal;
public Stock()
// default constructor
public Stock(String commandTwo, String ticker, Double price,
int etfDividendVal)
{
this.commandTwo = commandTwo;
this.ticker = ticker;
this.price = price;
this.etfDividendVal = etfDividendVal;
}
public String getTicker()
{
return ticker;
}
public String setTicker(String name)
{
ticker = name;
return ticker;
}
public Double getPrice()
{
return price;
}
public Double setPrice(Double namePrice)
{
price = namePrice;
return price;
}
#Override
public String toString()
{
return this.ticker + " " + this.price + "\t";
}
public abstract double calculatePrice();
}
ETF class
public class ETF extends Stock
{
public float numberOfStocks;
#Override
public double calculatePrice()
{
return (price * numberOfStocks);
}
}
Dividend class
public class Dividend extends Stock
{
public float yieldPercentage;
#Override
public double calculatePrice()
{
return (price * yieldPercentage);
}
}
It should look something like this
Pick an option: A-Add R-Remove P-Print C-Total cost Q-Quit
A
E
AMD
30.45
10
Pick an option: A-Add R-Remove P-Print C-Total cost Q-Quit
A
D
FXAIX
100
3
Pick an option: A-Add R-Remove P-Print C-Total cost Q-Quit
P
AMD 30.45 10.0
FXAIX 100.0 0.03
Pick an option: A-Add R-Remove P-Print C-Total cost Q-Quit
C
The total cost is: 307.4999999329448
You can still create an array Stock[], since ETF and Dividend both extend Stock, they can be added to the array. To use the methods declared in ETF and Dividend on the objects you retrieve from the array, you'll have to cast them, like so: ETF etf = (ETF) stk[someIndexHere];. Note that you don't know which objects are actually ETF and which are actually Dividend, and if you cast them to a type they actually aren't, you'll get an error. You can check if an object from stk is ETF or Dividend using the instanceof operator:
Stock stock = stk[0]; // Provided that there is a Stock at stk[0]
if (stock instanceof ETF) {
ETF etf = (ETF) stock;
// Now you can use etf as an ETF object
} else if (stock instanceof Dividend) {
// The second if-statement is redundant since there are only
// two possibilities, but in the future there might be more
// classes extending Stock
Dividend div = (Dividend) stock;
// Now you can use div as a Dividend object
}
Although since neither ETF nor Dividend implements any new methods, casting is unnecessary. instanceof too, unless you want to tell your user which type of stock they're dealing with.
I am doing a problem on inheritance and hierarchy of classes.
The problem is this: I have superclass that contains quantity as the attribute.
The code for that class is here:
class Items {
private int quantity;
public Items(int quantity) {
this.quantity = quantity;
}
Then i have two subclasses that contains prices and other attributes.
Code snippet:
class Coffee extends Items {
private String size;
public Coffee (int quantity, String size) {
super(quantity);
this.size = size;
}
}
class Donuts extends Items {
private double price;
private String flavour;
public Donuts(int quantity, double price, String flavour) {
super(quantity);
this.price = price;
this.flavour = flavour;
}
}
What i want to do is calculate the total price for each object.
My program reads a text file and creates object and stores them in an arrayList. The text file i am reading is this, Please note i have commented the first two lines just to explain what each token is, They are not included in the real file.:
Coffee,3,medium // name of item then the quantity and then size
Donut,7,0.89,chocolate // name then quantity then price then flavor
Donut,3,1.19,eclair
Coffee,1,large
I want to calculate the total price without duplication of the code. What i have done so far in my superclass is this:
public double totalPrice(Items x) {
double total = 0;
if(x instanceof Coffee) {
total = getQuantity() * getSizePrice();
} else {
if (x instanceof Donuts) {
total = totalPrice();
}
}
return total;
}
public abstract String getSizePrice();
In my Coffee subclass:
public double getSizePrice() {
double priceSmall = 1.39;
double priceMed = 1.69;
double priceLar = 1.99;
if(size == "small") {
return priceSmall;
} else {
if (size == "medium" ) {
return priceMed;
}
}
return priceLar;
}
I believe i am going in circles with this one so i was wondering if the SO community could guide me in the right direction. If the question is confusing, feel free to ask and i would explain it further.
Is it possible to get a totalPrice() method in each class and then through ploymorphism the class calculates the price of those items in the main method.
My code is working fine except for that the formatting is wrong. For example it is outputting:
Teriyaki $0.25 when I need it to output Teriyaki $.25. The only things outputting wrong are with the 0 in front of the decimal. the rest is correct. How can I fix this? Here is my code:
import java.text.NumberFormat;
public class MenuItem
{
private String name;
private double price;
public MenuItem (String name, double price)
{
this.name = name;
this.price = price;
}
public String getName()
{
return name;
}
public double getPrice()
{
return price;
}
public String toString()
{
return (getName() + " " + NumberFormat.getCurrencyInstance().format(getPrice()));
}
}
The test code is:
import java.util.Scanner;
import java.util.Vector;
public class sol
{
public static void main(String[] args)
{
/* Read from keyboard */
Scanner keys = new Scanner(System.in);
/* Create dynamic list */
Vector<MenuItem> list = new Vector<MenuItem>();
/* While there is input waiting */
while (keys.hasNext())
{
/* Prompt the user */
System.out.println("Enter product name and price");
/* Test the constructor */
list.add(new MenuItem(keys.next(), keys.nextDouble()));
}
/* Test toString (implicitly called when passed to println) */
System.out.println("Testing toString");
for (MenuItem mi : list)
System.out.println(mi);
/* Test getters */
System.out.println("Testing getters");
for (MenuItem mi : list)
System.out.println("Item: " + mi.getName() + " Price: " + mi.getPrice());
/* Close keyboard stream */
keys.close();
}
}
Thank you
Create a DecimalFormat to structure decimal numbers how you want them to appear
DecimalFormat twoDForm = new DecimalFormat("#.00");
Double d = Double.parseDouble("0.25");
String s = twoDForm.format(d);
System.out.println(s);
The # in the format indicates:
Digit, zero shows as absent
which will output .25 but still show a leading number if it is non zero
I have an assignment where I have to print US states by order of the highest to lowest percentage of eligible citizens enrolled in the Affordable Healthcare Act. I had to create an ArrayList and it holds two different types of data: two Strings and 3 doubles. I am very close to completion but I have been stumped at:
How do I print out the states line by line? I think I should use t/ to start a new line.
How do I print out the states in order of highest to lowest percentages?
Code so far.
import java.util.*;
import java.io.*;
import java.util.ArrayList;
// Calculates the percentage of citizens enrolled in the Affordable Healthcare Act
// Lists the states in order of highest percentage of enrolled citizens in the Affordable Healthcare Act
public class ACA {
public static void main( String[] args ) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in); // creates an object of the Scanner class
System.out.println("Enter filename"); // prompts the user for the name of the file
String filename = keyboard.next(); // the user response is stored
File inputFile = new File(filename+".txt"); // takes the filename and creates an object of the File class
Scanner fileIn = new Scanner(inputFile); // takes the object and converts the file to an obect of the Scanner class to allow it to be read
// creates an object of the ArrayList class
ArrayList<ACAdata> info = new ArrayList<>();
// variables declared for each column of data in the line
String state = " "; // State abbreviation
String org = " "; // Organizer of the ACA marketplace, either FFM for federally facilitated marketplace or SBM for state based marketplace.
double numEll = 0; // Number of citizens in the state eligible for ACA coverage
double numEn = 0; // Number of citizens who enrolled in an ACA plan
// while loop will evaluate as long as there are rows of data in the text file
while ( fileIn.hasNext() ) {
state = fileIn.next(); // individual state
org = fileIn.next(); // organization
numEll = fileIn.nextDouble(); // number of elligible citizens for that state for the Affordable Healthcare Act
numEn = fileIn.nextDouble(); // number of citizens enrolled in the Affordable Healthcare Act
double percentage = per( numEll, numEn ); // calls the per method to calculate a percentage for each state
// adds the 5 fields of data to a new ArrayList that holds the information for each state
info.add(new ACAdata( state, org, numEll, numEn, percentage));
}
// Prints out the information about the state
for ( int i = 0; i < info.size(); i++ ) {
System.out.println((info.get(i)).toString());
}
}
// method that finds the percentage of enrolled citizens that are elligible for the Affordable Care Act
public static double per( double Ell, double En ) {
double calculation = En / Ell * 100; // divides the Enrolled by the number of elligible citizens
return calculation; // returns the calculation
}
}
public class ACAdata {
// variables declared for each column of data in the line
String state = " "; // State abbreviation
String org = " "; // Organizer of the ACA marketplace, either FFM for federally facilitated marketplace or SBM for state based marketplace.
double numEll = 0; // Number of citizens in the state eligible for ACA coverage
double numEn = 0; // Number of citizens who enrolled in an ACA plan
double percentage = 0;
public ACAdata ( String state, String org, double numEll, double numEn, double percentage ) {
state = state;
org = org;
numEll = numEll;
numEn = numEn;
percentage = percentage;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getOrg() {
return this.org;
}
public void setOrg( String org ) {
this.org = org;
}
public double getNumEll() {
return this.numEll;
}
public void setNumEll( double numEll ) {
this.numEll = numEll;
}
public double getNumEn( double numEn ) {
return this.numEn;
}
public double getPercentage() {
return this.percentage;
}
public void setPercentage( double percentage ) {
this.percentage = percentage;
}
}
To make the ACAdata Object sortable.
If you have this Object you can sort it and then output it with.
ArrayList<ACAdata> list = new ArrayList<>();
Collections.sort(list);
for (Iterator<ACAdata> iterator = list.iterator(); iterator.hasNext();) {
ACAdata next = iterator.next();
System.out.println(next.toString());
}
public class ACAdata implements Comparable<ACAdata> {
// variables declared for each column of data in the line
String state = " "; // State abbreviation
String org = " "; // Organizer of the ACA marketplace, either FFM for federally facilitated marketplace or SBM for state based marketplace.
double numEll = 0; // Number of citizens in the state eligible for ACA coverage
double numEn = 0; // Number of citizens who enrolled in an ACA plan
double percentage = 0;
public ACAdata(String state, String org, double numEll, double numEn, double percentage) {
state = state;
org = org;
numEll = numEll;
numEn = numEn;
percentage = percentage;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getOrg() {
return this.org;
}
public void setOrg(String org) {
this.org = org;
}
public double getNumEll() {
return this.numEll;
}
public void setNumEll(double numEll) {
this.numEll = numEll;
}
public double getNumEn(double numEn) {
return this.numEn;
}
public double getPercentage() {
return this.percentage;
}
public void setPercentage(double percentage) {
this.percentage = percentage;
}
#Override
public int compareTo(ACAdata o) {
if (percentage > o.percentage) {
return -1;
}
if (percentage < o.percentage) {
return 1;
}
return 0;
}
#Override
public String toString() {
return "Put the info you want here!";
}
}
Looking at your code, the easiest solution (that I can think of) is to override toString in ACAdata with something like (add and format it how you want it)
#Override
public String toString() {
return String.format("%s %s %.2f %.2f", state, org, numEll, numEn);
}
And then you can just print the entire ArrayList, or individual ACAdata instances. You're already calling toString(), but you don't have to... Java will implicitly make a toString() call for you when you try and print an Object (the default implementation in Object just didn't do what you wanted).
import java.text.DecimalFormat; // For proper currency
import java.util.Arrays;
import java.util.Comparator;
public class Inventory {
public static void main( String args[] )
{
// Start array of software titles
Software[] aSoftware = new Software[4];
aSoftware[0]= new Software("Command and Conquer ", 6, 29.99, 10122);
aSoftware[1]= new Software("Alice in Wonderland", 1, 10.99,10233);
aSoftware[2]= new Software("Doom", 1, 10.99, 10344);
aSoftware[3]= new Software("Walking Dead", 6, 9.99, 10455);
//Set currency format
DecimalFormat money = new DecimalFormat("$0.00");
// Sort in order of Software Name
Arrays.sort(aSoftware, new Comparator<Software>() {
public int compare(Software s1, Software s2) {
return s1.getSoftwareTitle().compareTo(s2.getSoftwareTitle());
}
});
// Display software title, number of units, cost, item number and total inventory
for (int i = 0; i < aSoftware.length; i++){
System.out.println("Software Title is "+ aSoftware[i].getSoftwareTitle() );
System.out.println("The number of units in stock is "+ aSoftware[i].getSoftwareStock() );
System.out.println("The price of the Software Title is "+ (money.format(aSoftware[i].getSoftwarePrice() )));
System.out.println( "The item number is "+ aSoftware[i].getSoftwareNum());
System.out.println( "The year of copyright is "+ aSoftware[i].getYear());
System.out.println( "The restocking fee is "+ aSoftware[i].getRestockingFee());
System.out.println( "The value of the Software Inventory is "+ (money.format(aSoftware[i].Softwarevalue() )));
System.out.println();
}
//output total inventory value
double total = 0.0;
for (int i = 0; i < 3; i++){
total += aSoftware[i].getCalculateInventory();
}
System.out.printf("Total Value of Software Inventory is: \t$%.2f\n", total);
//end output total inventory value
}
} //end main
public class Software
{
// Declare variables
String SoftwareTitle;
int SoftwareStock;
double SoftwarePrice;
int SoftwareNum;
double CalculateInventory;
double SoftwareValue;
double value;
Software( String softtitle, int softstock, double softprice, int softitemnum )
{
// Create object constructor
SoftwareTitle = softtitle;
SoftwareStock = softstock;
SoftwarePrice = softprice;
SoftwareNum = softitemnum;
}
// Set Software Title
public void setSoftwareTitle( String softtitle )
{
SoftwareTitle = softtitle;
}
// Return Software Title
public String getSoftwareTitle()
{
return SoftwareTitle;
}
// Set software inventory
public void setSoftwareStock( int softstock)
{
SoftwareStock = softstock;
}
// Return software inventory
public int getSoftwareStock()
{
return SoftwareStock;
}
// Set software price
public void setSoftwarePrice( double softprice )
{
SoftwarePrice = softprice;
}
// Return software price
public double getSoftwarePrice()
{
return SoftwarePrice;
}
// Set item number
public void setSoftwareNum( int softitemnum )
{
SoftwareNum = softitemnum;
} //
//return software item number
public int getSoftwareNum()
{
return SoftwareNum;
} //
// calculate inventory value
public double Softwarevalue()
{
return SoftwarePrice * SoftwareStock;
}
public void setCalculateInventory (double value){
this.CalculateInventory = value;
}
public double getCalculateInventory(){
double value = 0;
for(int i = 0; i < 3; i++){
value = Softwarevalue();
}
return value;
}
}//end method value
//
public class Project3 extends Software
{
// Unique feature
private int year = 2012;
// Default Constructor
public Project3(String softtitle, int softstock, double softprice,int softitemnum, int year) {
super(softtitle, softstock, softprice, softitemnum);
this.year = year;
}
// Retuen Year
public int getYear()
{
return year;
}
// Set year
public void setYear(int year)
{
this.year = year;
}
// Calculate 5% restocking fee
public double getRestockingFee()
{
return getSoftwarePrice() * getSoftwareStock() * 0.05;
}
public double getCalculateInventory()
{
double value = 0;
for(int i = 0; i < 3; i++){
value = Softwarevalue();
}
return value;
}
}
My program runs fine except I can not get the my System out to pull over the getYear method and the getRestockingFee nethod from my Project 3 subclass. I could use a nudge in the right direction, I have to be missing something crazy.
The Java compiler, when given a Software object, has no way to know that it is really a Project3. In real life, if I put a Granny Smith apple in a box, and I tell you that there is an apple in the box, would you be able to tell me whether it boolean isGreen()? Java has the same problem!
There are possible 3 solutions:
When you construct the object, store it in a Project3 variable (and make sure the constructed type is a Project3!
Tell the JVM: "Hey this is really a Project3!" You can do this by casting the object to the correct time. Syntax ((Project3) mySoftware).getYear()
Define a meaning for the method getYear in the *super*class. This would be like telling you "hey, assume all Apples aren't green (isGreen() returns false)"... but if I know it's a Granny Smith subclass apple, isGreen returns true now!
Your choice of solution depends on what you want your system to do.