toString not outputting, simple hierarchy class program - java

I have two interfaces and two classes, Order class is parent of CoffeeBagOrder, There is no compiler error it just isn't displaying and I can't see why not
Order class:
public abstract class Order implements OrderInterface {
//variables
final static double SALES_TAX = 0.1; //not initialised by constructor
int unitWeight, numberOfUnits;
public Order() {
unitWeight=0;
numberOfUnits=0;
}
public Order(int unitWeight, int numberOfUnits) {
unitWeight=unitWeight;
numberOfUnits=numberOfUnits;
}
public void numberOfItems(int number) {
numberOfUnits=number;
}
public void unitWeight(int weight) {
unitWeight=weight;
}
}
CoffeeBagOrder class
public class CoffeeBagOrder extends Order implements Sales {
final static double PRICE_PER_KG = 5.55;
double salesBeforeTax;
double tax;
double totalSales;
public CoffeeBagOrder() {
}
public CoffeeBagOrder(int unitWeight, int numberOfUnits) {
super(unitWeight,numberOfUnits);
}
public double calculateSalesBeforeTax() {
salesBeforeTax= unitWeight*numberOfUnits*5.50;
return salesBeforeTax;
}
public double calculateSalesTax() {
tax=salesBeforeTax*0.10;
return tax;
}
public double calculateTotalSales() {
totalSales=salesBeforeTax+tax;
return totalSales;
}
//Override
public String toString() {
return "Price before tax: "+calculateSalesBeforeTax()+"\nTax: "+calculateSalesTax()+"\nTotal price: "+calculateTotalSales();
}
}
main
import java.util.Scanner;
public class Tester {
public static void main (String[] args) {
Scanner sc= new Scanner(System.in);
System.out.print("Enter number of bags sold: ");
int unitWeight=sc.nextInt();
System.out.print("Enter weight of bags in kilograms: ");
int numberOfUnits=sc.nextInt();
CoffeeBagOrder customer=new CoffeeBagOrder(unitWeight,numberOfUnits);
customer.toString();
}
}
I have omitted the interfaces but they are followed accordingly , thanks in advance, also I am unsure if I have efficiently written the constructors as they are both the same?

Change your Order class constructor like below (check this.):
public Order(int unitWeight, int numberOfUnits) {
this.unitWeight=unitWeight;
this.numberOfUnits=numberOfUnits;
}
You were not updating class field in constructor! It was assigning the parameter to itself.
And modify toString in CoffeeBagOrder like below (check annotation):
#Override
public String toString() {
return "Price before tax: "+calculateSalesBeforeTax()+"\nTax: "+calculateSalesTax()+"\nTotal price: "+calculateTotalSales();
}
Always use #Override annotation when you intend to override, to take it effect, which is best practice rather than calling toString() explicitly.
And print using
System.out.println(customer);

Related

Wanted to display the total cost of vacation including a percentage, but instead displays 0

I wanted to display the total cost of the vacation including a percentage, but it displays zero instead.
I'm just starting to learn oop, but this assignment made me hesitate about learning programming. I hope for your understanding!
I think it's about the formula in the account class.Either it's because of the wrong getters and setters. When I call season_num it shows 0 although it should have called 4,3,2 or 1 as it was in the setter
Main class
package com.company;
import java.util.*;
public class Main {
public static void main(String[] args) {
PriceCalculator pc= new PriceCalculator("summer","vip",5,50.25);
pc.displayAccount();
}
}
//Another class
package com.company;
public class PriceCalculator {
private int numberOfDays;
private double pricePerDay;
private String season;
private String typeDiscount;
private int season_num;
private int discount;
private double result;
PriceCalculator(String season, String typeDiscount, int numberOfDays, double pricePerDay){
this.numberOfDays=numberOfDays;
this.pricePerDay=pricePerDay;
this.season=season;
this.typeDiscount=typeDiscount;
}
String getSeason(){
return this.season;
}
void setSeason(String season){
if(season.equals("summer")){
season_num=4;
}
else if(season.equals("winter")){
season_num=3;
}
else if(season.equals("spring")){
season_num=2;
}
else if(season.equals("autumn")){
season_num=1;
}
}
String getTypeDiscount(){
return this.typeDiscount;
}
void setTypeDiscount(String typeDiscount){
if(typeDiscount.equals("vip")){
discount=20;
}
else if(typeDiscount.equals("secondvisit")){
discount=10;
}
}
int getNumberOfDays(){
return this.numberOfDays;
}
void setNumberOfDays(int numberOfDays){
this.numberOfDays=numberOfDays;
}
double getPricePerDay(){
return this.pricePerDay;
}
void setPricePerDay(double pricePerDay){
this.pricePerDay=pricePerDay;
}
double getResult(){
return this.result;
}
void setResult(double result){
this.result=result;
}
void displayAccount() {
class Account {
void displayAccountInfo() {
double res = pricePerDay * season_num * numberOfDays;
result= res-(res/discount);
System.out.println(result);
}
}
Account a= new Account();
a.displayAccountInfo();
}
}
The issue is in your constructor. You are not applying the setters with the custom logic you implemented. Try the following in your PriceCalculator class instead of the current constructor you have:
PriceCalculator(String season, String typeDiscount, int numberOfDays, double pricePerDay){
this.numberOfDays = numberOfDays;
this.pricePerDay = pricePerDay;
setSeason(season);
setTypeDiscount(typeDiscount);
}

Create different decorated object in case of input

Assume that I used decorated design pattern for making a pizza. There are 3 type of ingredients that user can add his pizza. Mozarella, souce and vegetables. I prepared these classes and set the cost.
This is main code
public class PizzaFactory {
public static void main(String[] args) {
Pizza p = new TomatoSauce(new Mozarella(new PlainPizza()));
System.out.println(p.getIngredients());
}
}
This is interface
public interface Pizza {
public String getIngredients();
public int getCost();
}
This is base pizza
public class PlainPizza implements Pizza{
#Override
public String getIngredients() {
return "Pizza ";
}
#Override
public int getCost() {
return 5;
}
}
This is decorator class
abstract class IngredientDecorator implements Pizza{
protected Pizza tempPizza;
public IngredientDecorator(Pizza newPizza) {
this.tempPizza = newPizza;
}
public String getIngredients() {
return tempPizza.getIngredients();
}
public int getCost() {
return tempPizza.getCost();
}
}
One of ingredient class is
public class Mozarella extends IngredientDecorator{
public Mozarella(Pizza newPizza) {
super(newPizza);
}
public String getIngredients() {
return tempPizza.getIngredients() + " Mozarella";
}
public int getCost() {
return tempPizza.getCost() + 1;
}
}
Others are look like them.
Now, I want to take input from user to which ingradient they want. In order to input I will create pizza. They may want just plain pizza. But since, I create my pizza -> Pizza p = new TomatoSauce(new Mozarella(new PlainPizza())); like this. How can I create pizza dinamic? Do I have to check each condition with if-else or switch-case?

count the number of objects created by java

I'm trying to count the number of objects created but it always returns 1.
public class Drivertwo {
public static void main(String[] args) {
Employee newEmp = new Employee();
Employee newEmp2 = new Employee();
Calculate newcal = new Calculate();
Clerk newclerk = new Clerk();
float x;
int y;
newEmp.setEmp_no(2300);
newEmp.setEmp_name("W.Shane");
newEmp.setSalary(30000);
newEmp.counter();
newEmp2.setEmp_no(1300);
newEmp2.setEmp_name("W.Shane");
newEmp2.setSalary(50000);
newEmp2.counter();
newclerk.setEmp_name("Crishane");
newclerk.setEmp_no(1301);
newclerk.setGrade(2);
newclerk.setSalary(45000);
newclerk.counter();
System.out.println("Salary is:" + newcal.cal_salary(newclerk.getSalary(), newclerk.getEmp_no()));
System.out.println("Name is:" + newclerk.getEmp_name());
System.out.println("Employee number is:" + newclerk.getEmp_no());
System.out.println("Employee Grade is:" + newclerk.getGrade());
System.out.println("No of objects:" + newEmp.numb);
This is my class with the main method
public class Employee {
private int salary;
private int emp_no;
private String emp_name;
public int numb=0;
public int getSalary() {
return salary;
}
public int getEmp_no() {
return emp_no;
}
public String getEmp_name() {
return emp_name;
}
public void setSalary(int newSalary) {
salary = newSalary;
}
public void setEmp_no(int newEmp_no) {
emp_no = newEmp_no;
}
public void setEmp_name(String newEmp_name) {
emp_name = newEmp_name;
}
}
public int counter() {
numb++;
return numb;
This is my Employee class
I tried to run counter in my employee class as a starter but it always returns 1. I know I can make a counter in main class and everytime I make a new object I can get the counter but I want to automatically increase the numb by 1 when an object is made.
You need to make numb static so that there will only be one copy for every instance of the class. As it is, every single Employee object has its own copy of numb.
Also instead of creating a method to up the counter why not just put it in the constructor:
public Employee() {
numb++;
}
numb is an instance variable, meaning that each Employee object will have its own numb, that will be initialized by 0.
If you want all the Employee instances to share the same numb, you should make it static.
// Java program Find Out the Number of Objects Created
// of a Class
class Test {
static int noOfObjects = 0;
// Instead of performing increment in the constructor instance block is preferred
//make this program generic. Because if you add the increment in the constructor
//it won't work for parameterized constructors
{
noOfObjects += 1;
}
// various types of constructors
public Test()
{
}
public Test(int n)
{
}
public Test(String s)
{
}
public static void main(String args[])
{
Test t1 = new Test();
Test t2 = new Test(5);
Test t3 = new Test("Rahul");
System.out.println(Test.noOfObjects);
}
}
Since static members initialized only once and it will be same for each and every instances of class.
class YourClass {
private static int numb;
public YourClass() {
//...
numb++;
}
public static int counter() {
return numb;
}
}
So simple;-
make this modifications
make numb static like, public int numb=0;,
remove numb++; from method count() and
create constructor public Employee{numb++;}

How do you shadow a final variable from a parent class?

I have a parent class in which i have a final static int which i need to shadow in a child class. In the parent class i use a method "print", which i override in my child class. If i use this code, the method print will use the MINIMUMPRIJS from my parent class. How can i make it use the MINIMUMPRIJS from my childclass?
In my taskdescription it says about the class "reis":
- Make sure the price is at least 5 euros. Create a variable for this and make sure this minimumprice is always guaranteed.
- 1 constructor with 1 paramter (destination)
- 1 constructor with paramters (destiantion, price)
about the class "vliegtuigreis"
- In here the minimumprice is 25 euros. Do what is needed.
- 1 constructor with just 1 paramater (destination)
- 1 constructor with paramaters (destination, price, and flightnumber)
public abstract class Reis {
public final static int MINIMUMPRIJS = 5;
public void setPrijs(double prijs) {
if (prijs >= getMINIMUMPRIJS()) {
this.prijs = prijs;
}else{
this.prijs = MINIMUMPRIJS;
}
}
public void print(){
System.out.printf("Reis met bestemming %s kost %,.2f euro. %n", bestemming, prijs);
}
}
public class VliegtuigReis extends Reis {
private final static int MINIMUMPRIJS = 25;
public void print(){
super.print();
System.out.println("Vluchtnr " + vluchtnummer);
}
}
You can define constants for default values, but then use fields to store dynamic values. You don't need to "shadow" the minimum price of the parent at all, you merely refer to a different constant in the child.
public abstract class Parent {
public static final double MIN_PRICE = 5.0;
private double price;
public Parent() {
this(MIN_PRICE);
}
public Parent(double price) {
this.price = Math.max(price, Parent.MIN_PRICE);
}
public print() {
System.out.println("Price is: " + this.price);
}
}
public class Child extends Parent {
private static final double MIN_PRICE = 25.0;
public Child() {
super(Child.MIN_PRICE);
}
public Child(double price) {
super(Math.max(price, Child.MIN_PRICE));
}
public void print() {
super.print();
System.out.println("Other stuff");
}
}
Hopefully you can take this and expand it to the rest of your requirements.

Using returns from two different methods in subclass

I'm struggling with one of the final parts of a school assignment.
I had asked this question on another question I had but did not receive an answer.
I have two methods in my super class that I need to use in my sub class and the one method must be invoked inside of the other to return a result, I'm stumped on how to do this.
public class Pay
{
private float hours;
private float rate;
private int hrsStr;
float gross;
double tax;
public void calc_Payroll()
{
if (hrsStr != 0)
gross = hrsStr + ((hours - hrsStr) * 1.33f) * rate;
else
gross = hours * rate;
}
public void tax(double a)
{
if (gross <= 399.99)
tax = .92;
else
if (gross <= 899.99)
tax = .88;
else
tax = .84;
}
public void setHours(float a)
{
hours = a;
}
public float getHours()
{
return hours;
}
public void setRate(float a)
{
rate = a;
}
public float getRate()
{
return rate;
}
public void setHrsStr(int a)
{
hrsStr = a;
}
public int getHrsStr()
{
return hrsStr;
}
}
That is the entire superclass and i need to call the calc_Payroll() method and the tax() method to the subclass, well I need tax() to be inside calc_Payroll() because I need to calculate the net pay from those two methods.
public class Payroll extends Pay
{
float net;
#Override
public void calc_Payroll()
{
//I need to calculate the the net pay here.
}
}
Are you struggling with the syntax of Java?
public class Payroll extends Pay
{
float net;
#Override
public void calc_Payroll()
{
// you can call `super.calc_Payroll()`
// you can call `tax(double a)`
}
}

Categories