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.
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 brand new in JAVA, and I didn't understand the line talking about "Item temp = (Item)obj;". What does the "(Item)" mean? Does it force to change type of obj? Please help me to figure it out, thanks!
public class Item implements Comparable {
private String id;
private String name;
private double retail;
private int quantity;
private double price;
Item(String idIn, String nameIn, String retailIn, String quanIn) {
id = idIn;
name = nameIn;
retail = Double.parseDouble(retailIn);
quantity = Integer.parseInt(quanIn);
if (quantity > 400)
price = retail * .5D;
else if (quantity > 200)
price = retail * .6D;
else
price = retail * .7D;
price = Math.floor( price * 100 + .5 ) / 100;
}
public int compareTo(Object obj) {
Item temp = (Item)obj;
if (this.price < temp.price)
return 1;
else if (this.price > temp.price)
return -1;
return 0;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public double getRetail() {
return retail;
}
public int getQuantity() {
return quantity;
}
public double getPrice() {
return price;
}
}
Item temp = (Item)obj; is performing type conversion (or typecasting) Object obj to the type Item. If obj is not an Item, then it will throw a ClassCastException, the Javadoc of which says (in part)
Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException:
Object x = new Integer(0);
System.out.println((String)x);
However, because Comparable is generic, it's also possible to make Item like
public class Item implements Comparable<Item>
and then compareTo(Item) like
#Override
public int compareTo(Item temp) {
return Double.compare(this.price, temp.price);
// if (this.price < temp.price)
// return 1;
// else if (this.price > temp.price)
// return -1;
// return 0;
}
This line: Item temp = (Item)obj;
Taking another object of this class for comparing. This is for sorting of group/list of item class objects.
So When we will sort list of Item, It will take this(current) object with the passing object of this class.
This is known as the casting(Genrally its categorised in two type Down & Up Casting).
Casting allows the use of generic programming in Java,
where code is written to work with all objects of classes descended from some base class (often java.lang.Object, for utility classes).
However, the use of casting causes a unique set of problems.If you try to cast two object which doesn't share same type hierarchy,
i.e. there is no parent child relationship between them, you will get compile time error.On the other hand if you type cast objects from same type hierarchy butthe object which you are casting are not of the same type on which you are casting then it will throw ClassCastException in Java.
And #Elliot have already explained it by example
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 7 years ago.
Improve this question
So I'm basically completely lost in regards to where I'm supposed to go with this assignment. This is what the assignment is asking me to do.
"Part I:
Design a class named Item that has information about items that are for sale in a store. An Item has the following properties: Name, Vendor, Price, Weight, Taxable (a boolean field that indicates whether or not tax is charged on the item).
Part II:
Design a ShoppingCart class that contains items. Several interesting methods are
AddItem to insert an item to the cart.
CartTotal computes the total price of the cart.
CartTaxAmount receives the tax rate and computes the total tax to charge for the items currently in the cart. Only Taxable items should be considered for this calculation.
If it makes things easier, you can assume that the capacity of a ShoppingClass is fixed at 10 items.
Keep in mind:
Each class should have at least one constructor that receives arguments.
Make data members private and create accessor and mutator methods whenever necessary.
Each class should have a toString method that you use to display the contents of the class.
Write a standalone function that allows a user to enter information for an Item and returns an Item to the calling function.
"
I'm just not wrapping my head around how to store a class item in an array of another class.
import java.util.Scanner;
class Item {
//data members
private String Name;
private String Vendor;
private double Price;
private double Weight;
private boolean Taxable;
//constructor
Item(String conName, String conVendor, double conPrice, double conWeight, boolean Tax)
{
Name = conName;
Vendor = conVendor;
Price = conPrice;
Weight = conWeight;
Taxable = Tax;
}
//Aceessor methods
public String getname(){
return Name;
}
public String getvendor(){
return Vendor;
}
public double getprice(){
return Price;
}
public double getweight(){
return Weight;
}
public boolean gettaxable(){
return Taxable;
}
public String toString()
{
String s = "Item Name is " + Name + " and the vendor is " + Vendor + ". The Price of the item is " + Price + " and the weight of the item is " + Weight + ". Item is taxable = " + Taxable + ".";
return s;
}
}
public class ShoppingCart {
private Item[] itemsToBuy;
private double taxRate;
private int numItems;
ShoppingCart(int capacity, double taxamount) {
itemsToBuy = new Item[capacity];
taxRate = taxamount;
numItems = 0;
}
//Accessor methods
public double gettaxRate(){
return taxRate;
}
public int getItemNum() {
return numItems;
}
public Item getitemsToBuy(int i) {
return itemsToBuy[i];
}
//Methods
public void AddItem() {
}
Keep your head up; you're on the right track. You can pass an item to the AddItem method and then insert it in your itemsToBy array. You just have to check to make sure there's room in the cart.
Try this:
public void AddItem(Item item) {
if(numItems < itemsToBuy.length){
itemsToBuy[numItems] = item; //insert item in the array
numItems++; //increment the number of items
} else {
System.out.println("Your cart is full.");
}
}
Why don't you try to implement a removeLastItem() method that removes the newest item from the cart. This should help you practice.
I recommend you watch the Java for Complete Beginners videos at CaveofProgramming.com. They were very helpful when I first started learning Java.
I cannot give you a ready made answer since this is obviously a homework assignment that you are supposed to do. But here are a few pointers that will help you understand the problem more:
Item
You need to create a public class called Item. That would look similar to what you already have, except a few changes that you could make:
Make the class public (public class Item)
You don't need a big constructor like this. Since you have the mutator methods, you can keep you constructor default like the following:
public class Item {
public Item() {
// default constructor
}
...
}
Change your getters/setters to use the getXyz and setXyz forms for each private member xyz. Notice the uppercase X, followed by lowercase yz.
You don't need to print a statement in your toString() method; it will become long and will fill up your console with unnecessary text. Instead make it simple and concise. Also, make a practice of using StringBuilder to build a string instead of using string concatenation. While string concatenation is not necessarily bad, StringBuilder keeps it less controversial :)
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getName()).append("\n")
.append("\t name: ").append(getName()).append("\n")
.append("\t vendor: ").append(getVendor()).append("\n");
// do the same for all fields
return sb.toString();
}
ShoppingCart
You will need a public class called ShoppingCart that would contain a List of Item objects; something like the following:
<pre>
import java.util.List;
import java.util.ArrayList;
public class ShoppingCart {
private final List<Item> items; // items can be of any size
private double taxRate;
public ShoppingCart() {
this.items = new ArrayList<Item>();
}
// getter for items List
public List<Item> getItems() {
return this.items;
}
// instead of a setter, we have an 'adder' which
// adds one element. you can call this method
// to add items one at a time to the items List
public void addItem(Item item) {
this.items.add(item);
}
// or you can use a varargs adder, using which
// you have the convenience of adding more than
// one item at a time
public void addItem(Item... items) {
if(items != null && items.length > 0) {
for(Item item : items) {
this.items.add(item);
}
}
}
// getter for taxRate
public double getTaxRate() {
return this.taxRate;
}
// setter for taxRate
public void setTaxRate(double taxRate) {
this.taxRate = taxRate < 0 ? 0 : taxRate;
}
// item count is calculated; it's not a field getter
public int getItemCount() {
return this.items.size();
}
// calculates total price without taxes
public double calculateCartPriceTotalNoTax() {
double total = 0.0;
for(Item item : this.items) {
total += item.getPrice();
}
return total;
}
// calculates total price with taxes
public double calculateCartPriceTotal() {
double totalNoTax = calculateCartPriceTotalNoTax();
double total = totalNoTax * getTaxRate() / 100;
return total;
}
// calculates total price with taxes (different way of doing it)
public double calculateCartPriceTotal2() {
double total = 0.0;
double taxRate = getTaxRate();
for(Item item : this.items) {
total += (item.getPrice() * getTaxRate() / 100);
}
return total;
}
// toString method for the ShoppingCart.
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getName()).append("\n")
.append("\t items: ").append(getItems()).append("\n")
.append("\t taxRate: ").append(getTaxRate()).append("\n")
.append("\t totalPriceNoTax: ").append(calculateCartPriceTotalNoTax()).append("\n")
.append("\t totalPriceWithTax: ").append(calculateCartPriceTotal()).append("\n");
return sb.toString();
}
}
</pre>
Note:
May be you should start using Eclipse (or IntelliJ Idea, if you like). It will make writing Java code much easier, and will help you avoid many errors.
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.?
I have to write a program that uses two classes to create a grocery list. The first class creates an array to hold the values gotten from the second class. The array holds grocery items which have a name, quantity, and price value. I have a function that is supposed to get a total cost of everything in the array, but for some reason the function is only adding the last item that is added to the array to itself. Here's my code:
public class GroceryList {
private GroceryItemOrder[] groceryList = new GroceryItemOrder[0];
private int numofEntries;
public GroceryList()
{
this.groceryList = new GroceryItemOrder[10];
this.numofEntries = 0;
}
public void add(GroceryItemOrder item)
{
if(numofEntries == 10)
{
System.out.println("The list is full.");
}
else
{
groceryList[numofEntries] = item;
numofEntries++;
}
}
public double getTotalCost()
{
double totalCost = 0;
double newCost = 0;
for(int size = 0; size < numofEntries; size ++)
{
newCost = groceryList[size].getCost();
totalCost = newCost + totalCost;
}
return totalCost;
}
public class GroceryItemOrder {
private static double pricePerUnit;
private static int quantity;
private String name;
public GroceryItemOrder(String name, int quantity, double pricePerUnit)
{
this.name = name;
this.quantity = quantity;
this.pricePerUnit = pricePerUnit;
}
public static double getCost()
{
return (quantity * pricePerUnit);
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
public static void main(String[] args)
{
GroceryList newList = new GroceryList();
newList.add(new GroceryItemOrder("cookies", 1, 1.50));
newList.add(new GroceryItemOrder("cheese", 2, 1.0));
newList.add(new GroceryItemOrder("bread", 1, 5.0));
System.out.println(newList.getTotalCost());
}
}
In the function I was trying to use a for loop that would run through the array one element at a time and take whatever values were stored into the element and store it into a new object. I feel like I'm heading in the right direction but can't figure out where the issue is with the function. Can anyone see where my issue is, or at least give me some advice on how I can begin to attempt to fix the issue?
2 of your 3 variables in GroceryItemOrder are static, which means only one variable for the entire class, not one for each instance. Each new instance overwrites the values set by the previously created instance.
Make all of those instance variables not static:
private double pricePerUnit;
private int quantity;
private String name;
The static modifier to quantity and pricePerUnit makes no sense if you want to have some variety in your grocery. What happens is that each time you call the constructor or GroceryItemOrder, you change those two static fields, so if affects the total price of all the previous orders created. The rest is fine even if it could be more concise sometimes.