java:29: error: cost has private access in RetailItem - java

Alright so I need help here I created a cash register java file and a retailItem file in my cash register file it cant read a section i put in retailItem because its private. So my question is how do i access that private variable that i wrote in my retailItem class into the cash register file
So here's my code for retailItem
import java.text.DecimalFormat;
public class RetailItem
{
private String description;
private double price;
private double unitsOnHand;
private CostData cost;
public void setDescription(String userDescription)
{
description = userDescription;
}
public void setPrice(double p)
{
price = p;
}
public void setUnitsOnHand(double userUnitsOnHand)
{
unitsOnHand = userUnitsOnHand;
}
public String getDescription()
{
return description;
}
public double getPrice()
{
return price;
}
public double getUnitsOnHand()
{
return unitsOnHand;
}
public RetailItem(RetailItem object2)
{
description = object2.description;
price = object2.price;
unitsOnHand = object2.unitsOnHand;
cost = new CostData(object2.cost.wholeSale,object2.cost.Retail);
}
public RetailItem( String descriptionGet,double pri, double
unitsOnHandGet,double wholeSale,double retail)
{
description = descriptionGet;
price = pri;
unitsOnHand = unitsOnHandGet;
cost = new CostData(wholeSale,retail);
}
public String toString()
{
String str;
DecimalFormat dollar = new DecimalFormat("#,##0.00");
str = "Description: " + description +
"Item Price: " + price +
"\nItem Number: " + unitsOnHand +
"\nWhole Cost: $" + dollar.format(cost.wholeSale) +
"\nRetail Price: $" + dollar.format(cost.Retail);
return str;
}
public class CostData
{
public double wholeSale;
public double Retail;
public CostData(double whole,double re)
{
wholeSale = whole;
Retail = re;
}
public void setRetail(double re)
{
Retail = re;
}
public void setWholeSale(double whole)
{
wholeSale = whole;
}
public double getRetail()
{
return Retail;
}
public double getWholeSale()
{
return wholeSale;
}
}
}
Here is the Cash Register class:
public class CashRegister
{
private RetailItem retail;
private int quantityItem;
private final double SALES_TAX = 0.06;
private int subTotal;
public CashRegister()
{
quantityItem = 0;
subTotal = 0;
}
public CashRegister(RetailItem retailObject,int quantity)
{
retail = new RetailItem(retailObject);
quantityItem = quantity;
}
public RetailItem getRetailItem()
{
return new RetailItem(retail);
}
public double getSubTotal()
{
return quantityItem * retail.cost.getRetail();//Here is where the problem is
}
public double getTax()
{
return SALES_TAX;
}
public double getTotal()
{
return subTotal + SALES_TAX;
}
}

You have a number of options:
If they are in the same package, you can set the access of cost to
default (remove the word private from in front of it.)
Change cost from private to public.
Create a default access (neither private nor public) getCost() method to return cost.
Create a public getCost() method to return cost.
The first option gives read/write access to any class in the same package as RetailItem.
The second option gives read/write access to all classes.
The fourth option gives read-only access to all classes.
protected access could also be an option. Its like package access, but also gives read/write access to subclasses.
See also: In Java, difference between default, public, protected, and private

Related

How to format output console columns in java?

I'm made a program that creates an invoice but when it comes numbers in the thousands the output isn't neat and ruins everything. How do I fix this so the program's columns are more aligned with numbers like this? Here is the code I used to create the program. If anyone could help, it would be much appericated.
Here's the one with the main method...
public class InvoicePrinter
{
public static void main(String[] args)
{
Address samsAddress=new Address("Sam's Small Appliances", "100 Main
Street", "Anytown", "CA", "98765");
Invoice samsInvoice =new Invoice(samsAddress);
samsInvoice.add(new Product("Toaster", 29.95),3);
samsInvoice.add(new Product("Hair Dryer", 24.95),1);
samsInvoice.add(new Product("Car Vacuum",19.99),2);
samsInvoice.add(new Product("Nano Parts",100000),1);
samsInvoice.addSimple(new Product("Shipping",5.00));
System.out.println(samsInvoice.format());
}
}
These are the other programs needed for the program to work
import java.util.ArrayList;
public class Invoice
{
public Invoice(Address anAddress)
{
items=new ArrayList<LineItem>();
billingAddress=anAddress;
simpleItems= new ArrayList<SimpleLineItem>();
}
public void addSimple(Product aProduct)
{
SimpleLineItem anItem= new SimpleLineItem(aProduct);
simpleItems.add(anItem);
}
public void add(Product aProduct, int quantity)
{
LineItem anItem=new LineItem(aProduct,quantity);
items.add(anItem);
}
public String format()
{
String r=" I N V O I C E\n\n"+billingAddress.format()+String.format("\n\n%-30s%8s%5s%8s\n","Description", "Price","Qty","Total");
for(LineItem i:items)
{
r=r+i.format()+"\n";
}
for(SimpleLineItem j:simpleItems)
{
r=r+j.format() + "\n";
}
r = r + String.format("\nAMOUNT DUE: $%8.2f", getAmountDue());
return r;
}
public double getAmountDue()
{
double amountDue = 0;
for (LineItem i : items)
{
amountDue = amountDue + i.getTotalPrice();
}
for(SimpleLineItem j:simpleItems)
{
amountDue = amountDue + j.getPrice();
}
return amountDue;
}
private Address billingAddress;
private ArrayList<LineItem> items;
private ArrayList<SimpleLineItem> simpleItems;
}
Few more
public class LineItem
{
public LineItem(Product aProduct, int aQuantity)
{
theProduct = aProduct;
quantity = aQuantity;
}
public double getTotalPrice()
{
return theProduct.getPrice() *quantity;
}
public String format()
{
return String.format("%'-30s%'8.2f%'5d%'8.2f", theProduct.getDescription(),theProduct.getPrice(),quantity,getTotalPrice());
}
private int quantity;
private Product theProduct;
}
Another one
public class SimpleLineItem
{
public SimpleLineItem(Product aProduct)
{
theProduct=aProduct;
}
public double getPrice()
{
return theProduct.getPrice();
}
public String format()
{
return String.format("%-30s" +" " + "%8.2f",
theProduct.getDescription(), theProduct.getPrice());
}
private Product theProduct;
}
Two more
public class Product
{
public Product(String aDescription,double aPrice)
{
description = aDescription;
price = aPrice;
}
public String getDescription()
{
return description;
}
public double getPrice()
{
return price;
}
private String description;
private double price;
}
Last one
public class Address
{
public Address(String aName, String aStreet, String aCity, String
aState,String aZip)
{
name = aName;
street = aStreet;
city = aCity;
state = aState;
zip = aZip;
}
public String format()
{
return name + "\n" + street + "\n" + city + ", " + state + " " + zip;
}
private String name;
private String street;
private String city;
private String state;
private String zip;
}
Maybe you can take a look at the javadocs by Oracle on System.out.format and DecimalFormat class
Formatting Numeric Print Output
So basically this happens when you cannot decide the total length of your number column until you print out everything. For this you will need to set the number column's length to the lengthiest number or in your case price length and justify right all the numbers. So you'll need to add all the numbers to an array and loop through them to find the lengthiest number.

How do I call a method from a parent of a parent of an inherited class? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
public class TimsOrder {
private int size;
private String name;
private static TimsProduct[] items;
private TimsOrder(String name, int size) {
this.name = name;
this.size = size;
}
#Override
public double getRetailPrice(){
return price;
}
private static void orderItem(TimsProduct item) {
Donut chocolate = Donut.create();
item = chocolate;
}
public static TimsOrder create() {
items = new TimsProduct[size];
for (int i = 0; i < items.length; i++) {
orderItem(items[i]);
}
TimsOrder order = new TimsOrder("OrderName", 1); //Where 1 is the # of items
}
public double getAmountDue() {
double total = 0;
System.out.println("Testpoint");
for (int i = 0; i < items.length; i++) {
total = total + (((TimsProduct) items[i]).getRetailPrice()); //Line with issue
}
return total;
}
}
public abstract class TimsProduct extends Commodity {
private String name;
private double cost;
private double price;
#Override
public double getRetailPrice(){
System.out.println("Testpoint2");
return price;
}
}
public class Donut extends TimsProduct {
private String description;
private int calorieCount;
private Donut(String name, String description, double cost, double price, int calorieCount) {
super(name, cost, price);
this.description = description;
this.calorieCount = calorieCount;
}
public static Donut create() {
Donut chocolate = new Donut("Chocolate", "Glazed", 0.30, 0.99, 500);
return chocolate;
}
}
Test Code:
TimsOrder t = TimsOrder.create();
System.out.println(t);
System.out.printf("Total Price: $%.2f\n", t.getAmountDue());
I realize that t.items has 0 values which is the problem here. What I do not know is why these values are not there.
If anyone wants to see the files:
Commodity.java
https://pastebin.com/raw/9sWbDWV8
TimsProduct.java extends commodity
https://pastebin.com/raw/jzgfkd0P
TimsOrder.java
https://pastebin.com/raw/vc0VtDq6
Donut.java extends TimsProduct
https://pastebin.com/raw/w7iEQG1H
This is an initial response based on what little the OP provided.
You are not overriding your getters in your deriving classes (and the basic implementation in the base can not compile) :
public abstract class Commodity {
public double getProductionCost() {
// no return value!
}
public double getRetailPrice() {
// no return value!
}
}
public abstract class TimsProduct extends Commodity{
private String name;
private double cost;
private double price;
public TimsProduct(String name, double cost, double price){
this.name = name;
this.cost = cost;
this.price = price;
}
public String getName(){
return name;
}
// no #Override!
public double getProductionCost(){
return cost;
}
// no #Override!
public double getRetailPrice(){
return price;
}
public String toString(){
return ("Name is: " + name + "cost is: " + cost + "price is: " + price );
}
}

I dont get the expected output from my java application

I got 5 classes, and 4 of them are working as intended.
I'm an absolut beginer with java and I hope someone can provide me with help.
its a little application to make orders and bundle orders.
my problem is the class bundleItem.
I expect to get the value of all items with a discount added to them, but I allways get negative return values.
Here are my classes
class Order
package testateins;
import java.util.ArrayList;
public class Order {
private ArrayList<Item> allOrders;
public Order(){
this.allOrders = new ArrayList<Item>();
}
public void addItem(Item item) {
this.allOrders.add(item);
}
public void removeItem(Item item) {
this.allOrders.remove(item);
}
public double getTotalprice(){
double totalprice = 0;
for(Item element : allOrders) {
totalprice += element.getPrice();
}
return totalprice;
}
public void printItems() {
for(Item element : allOrders) {
element.print();
}
}
}
Class Item
package testateins;
public abstract class Item{
String description;
double price;
public Item(String description) {
this.description = description;
}
public abstract double getPrice();
public void setItem() {
}
public void print() {
System.out.println("Beschreibung " + description);
}
}
class ProductItem
package testateins;
public class ProductItem extends Item{
public double pricePerUnit;
public double amount;
public double price;
public ProductItem(String description, int pricePerUnit, int amount) {
super(description);
this.pricePerUnit = pricePerUnit;
this.amount = amount;
this.price = amount * pricePerUnit;
}
public void print() {
System.out.println("Beschreibung " + description);
System.out.println("menge " + amount);
System.out.println("Preis pro Einheit " + pricePerUnit);
System.out.println("Gesammtpreis " + price);
}
public double getPrice() {
return this.price;
}
}
class ServiceItem
package testateins;
public class ServiceItem extends Item{
public double price;
public ServiceItem(String description, Integer packageprice) {
super(description);
this.price = packageprice;
}
public void print() {
System.out.println("Beschreibung " + description);
System.out.println("Servicepreis " + price);
}
public double getPrice() {
return this.price;
}
}
class BundleItem(my problemclass)
package testateins;
import java.util.ArrayList;
public class BundleItem extends Item {
private double rabatt;
private ArrayList<Item> allOrders;
public BundleItem(String description, double rabatt) {
super(description);
this.allOrders = new ArrayList<Item>();
setrabatt(rabatt);
}
public void setrabatt(double rabatt) {
this.rabatt = rabatt;
}
public double getrabatt() {
return this.rabatt;
}
public void addItem(Item item) {
if(item instanceof ProductItem || item instanceof ServiceItem) {
this.allOrders.add(item);
}
}
#Override
public double getPrice() {
double result = 0;
double sum = 0;
double discount = (rabatt/100);
for(Item element : allOrders) {
result+=element.getPrice();
}
return sum - (result * discount);
}
public void print() {
super.print();
System.out.println(rabatt);
for(Item element: allOrders) {
element.print();
}
}
}
and my testing class which returns negative discounts, the important part is after "part 2"
package testateins;
public class Testing {
public static void main(String[] args) {
ServiceItem wischen = new ServiceItem("wischen", 20);
System.out.println(wischen.description);
System.out.println(wischen.price);
System.out.println("___________________________");
ProductItem kuchen = new ProductItem("kuchen", 3, 15);
System.out.println(kuchen.description);
System.out.println(kuchen.amount);
System.out.println(kuchen.pricePerUnit);
System.out.println(kuchen.price);
System.out.println("___________________________");
Order simpleOrder = new Order();
simpleOrder.addItem(wischen);
simpleOrder.addItem(kuchen);
simpleOrder.addItem(kuchen);
simpleOrder.printItems();
System.out.println("___________________________");
System.out.println("totalpreis:");
System.out.println(simpleOrder.getTotalprice());
//part 2
System.out.println("--------uebung 2------------.-");
Order BundleOrder = new Order();
ProductItem heft = new ProductItem("Heft", 1, 10);
ProductItem stift = new ProductItem("Stift", 1, 10);
BundleItem Discounteins = new BundleItem("Discounteins(50)", 50);
BundleItem Discountzwei = new BundleItem("Discountzwei(50)", 50);
BundleItem Discountdrei = new BundleItem("Discounteins(10)", 10);
Discounteins.addItem(heft);
Discounteins.addItem(stift);
Discountzwei.addItem(Discounteins);
Discountzwei.addItem(wischen);
Discountzwei.addItem(wischen);
Discountdrei.addItem(wischen);
Discountdrei.addItem(wischen);
BundleOrder.addItem(Discountzwei);
BundleOrder.addItem(Discounteins);
BundleOrder.printItems();
System.out.println(BundleOrder.getTotalprice());
System.out.println("---------------------------.-");
Discounteins.setrabatt(50);
System.out.println(Discounteins.getrabatt());
BundleOrder.printItems();
System.out.println("---------------------------.---");
System.out.println(BundleOrder.getTotalprice());
System.out.println("---------------------------.----");
}
}
Your sum is always zero, that's why you always get negative values.
I suppose you intended to do something like this:
#Override
public double getPrice() {
double sum = 0;
double discount = (rabatt / 100);
for(Item element : allOrders) {
sum += element.getPrice();
}
return sum - (sum * discount);
}
Try replacing
return sum - (result * discount);
with
return result-(result * discount);
and remove the sum variable that is not used. Now
(result * discount)
will give you the total discount. And Subtracting it from result will give you the actual amount after discounts

Can i create a subclass object for a dynamic Array List super class type object?

If i wanted to use a Dynamic Array List which is initializing class Worker can i add sub-classes that extend the Worker class and try to fill them with data like the following test class?.. whenever i try calling a certain function that one of the sub-classes have i get an error , I need to call these functions so how can i do it correctly?
public class Worker extends Person {
private int id;
Worker() {
}
Worker(int i) {
id = i;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String toString() {
return super.toString() + "ID: " + id + " ";
}
}
public class HourlyWorker extends Worker implements Annual {
private double rate;
private double AnnualPayment;
private double percentageIncrease;
HourlyWorker() {
}
HourlyWorker(double r) {
rate = r;
}
public double getAnnualPay(double Annualpayment) {
return Annualpayment = rate * 52 * 40;
}
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
public double getAnnualPayment() {
return AnnualPayment;
}
public void setAnnualPayment(double AnnualPayment) {
this.AnnualPayment = AnnualPayment;
}
public double getpercentageIncrease() {
return percentageIncrease;
}
public void setpercentageIncrease(double percentageIncrease) {
this.percentageIncrease = percentageIncrease;
}
public void increasePayment(double r) {
increasePayR(r);
}
public double increasePayR(double r) {
return rate = (AnnualPayment + getAnnualPay(r) * percentageIncrease) / 2080;
}
public String toString() {
return "Your rate : " + rate + " ";
}
}
public class SalariedWorker extends Worker implements Annual {
private double salary;
private double AnnualPayment;
private double percentageIncrease;
SalariedWorker() {
}
SalariedWorker(double s) {
salary = s;
}
public double getAnnualPay(double Annualpayment) {
return Annualpayment = salary * 12;
}
public void increasePayment(double r) {
increasePayS(r);
}
public double increasePayS(double r) {
return salary = (AnnualPayment + getAnnualPay(r) * percentageIncrease) / 12;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getAnnualPayment() {
return AnnualPayment;
}
public void setAnnualPayment(double AnnualPayment) {
this.AnnualPayment = AnnualPayment;
}
public double getpercentageIncrease() {
return percentageIncrease;
}
public void setpercentageIncrease(double percentageIncrease) {
this.percentageIncrease = percentageIncrease;
}
public String toString() {
return " ";
}
}
public class Test {
public static void main(String[] args) {
Scanner prompt = new Scanner(System.in);
ArrayList<Worker> Worker1 = new ArrayList<Worker>();
Worker1.add(new SalariedWorker());// is it alright to create a subclass object here?
Worker1.add(new SalariedWorker(1000.0));// index 1
Worker1.add(new HourlyWorker());// index 2
Worker1.add(new HourlyWorker(100.0));// index 3
System.out.println("Enter your monthly salary: ");
double salary = prompt.nextDouble();
Worker1.get(0).getSalary(salary);//gets me an error
System.out.println("Enter your hourly rate: ");
double HourlyRate = prompt.nextDouble();
System.out.println("Enter the Percentage Increase for a Salaried worker: ");
double PercentIncreaseS = prompt.nextDouble();
Worker1.get(0).getpercentageIncrease(PercentIncreaseS);//gets me an error
System.out.println("Your Increased payment is: ");
System.out.println("Enter the Percentage Increase for an Hourly worker: ");
double PercentIncreaseH = prompt.nextDouble();
}
}
You are getting the error because the Worker class does not have a getSalary() method.
You need to cast the objects in the list to the appropriate sub-class type.
For example:
SalariedWorker sw = (SalariedWorker) Worker1.get(0);
sw.getSalary(salary);
Problem with below code fragment is:
ArrayList<Worker> Worker1 = new ArrayList<Worker>();
Worker1.get(0).getSalary(salary);
get will return you the abstraction which doesn't have the getSalary(salary) method. All you have to do is to cast each with respective implementation class and the invoke the method on it.
Ex:
SalariedWorker sw = (SalariedWorker)Worker1.get(0);

How do I override a method in a subclass?

I have an inventory program written to include an array and a method to calculate total cost for all inventory items entered. I now have to include a subclass that overrides the original to include "one unique feature". I created a new file named ItemDetails to set up for the subclasses of the original Item. I need to include one unique feature and calculate the value of the inventory and calculate a 5% restocking fee in this subclass. Do I just transfer some of the relevant lines into the other class? Or do I write some code twice? I don't know what to do next. Any help is useful. Thanks. This is what I have so far:
package inventory3;
public class ItemDetails extends Items
{
public static void override()
{
private String Name;
private double pNumber, Units, Price;
public ItemDetails()
{
}
}
}
This is the Item class file that it is supposed to override:
package inventory3;
import java.lang.Comparable;
public class Items implements Comparable
{
private String Name;
private double pNumber, Units, Price;
public Items()
{
Name = "";
pNumber = 0.0;
Units = 0.0;
Price = 0.0;
}
public int compareTo(Object item)
{
Items tmp = (Items) item;
return this.getName().compareTo(tmp.getName());
}
public Items(String productName, double productNumber, double unitsInStock, double unitPrice)
{
Name = productName;
pNumber = productNumber;
Units = unitsInStock;
Price = unitPrice;
}
//setter methods
public void setName(String n)
{
Name = n;
}
public void setpNumber(double no)
{
pNumber = no;
}
public void setUnits(double u)
{
Units = u;
}
public void setPrice(double p)
{
Price = p;
}
//getter methods
public String getName()
{
return Name;
}
public double getpNumber()
{
return pNumber;
}
public double getUnits()
{
return Units;
}
public double getPrice()
{
return Price;
}
public double calculateTotalPrice()
{
return (Units * Price);
}
public static double getCombinedCost(Items[] item)
{
double combined = 0;
for(int i =0; i < item.length; ++i)
{
combined = combined + item[i].calculateTotalPrice();
}
return combined;
}
}
You simply declare a method with the same signature as the method in the parent class. So yours would look like:
package inventory3;
public class ItemDetails extends Items {
private String Name;
private double pNumber, Units, Price;
public ItemDetails(String Name, double pNumber, double Units, double Price) {
this.Name = Name;
this.pNumber = pNumber;
this.Units = Units;
this.Price = Price;
}
// getters and setters....
// The #Override is optional, but recommended.
#Override
public double calculateTotalPrice() {
return Units * Price * 1.05; // From my understanding this is what you want to do
}
}

Categories

Resources