Divide values from a class extending number - java

I have a class which extends number.
public class Quantity extends Number{
}
And the class as,
public class Test{
Quantity tkphMaxValue;
Quantity tkphValue;
public Test(Quantity tkphValue, Quantity maxValue){
this.tkphValue= tkphValue;
this.maxValue= maxValue;
}
public Quantity getTkphValue() {
return tkphValue;
}
public void setTkphValue(Quantity tkphValue) {
this.tkphValue = tkphValue;
}
public Quantity getTkphMaxValue() {
return tkphMaxValue;
}
public void setTkphMaxValue(Quantity maxValue) {
this.tkphMaxValue = maxValue;
}
}
I need to divide ((getTkphValue()/getTkphMaxValue())*100) to get the percentage value.
How can I convert the Quantity object to number?

Try this:
((getTkphValue().doubleValue()/getTkphMaxValue().doubleValue())*100)
Before you do, make sure that tkphMaxValue and tkphValue are not null.

Related

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?

toString not outputting, simple hierarchy class program

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

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++;}

Hashmap method to sum

so i have the following task:
Given is the following class:
public class Konto {
private final String inhaber;
private double guthaben;
public Konto(String inhaber) {
this.inhaber = inhaber;
}
public String getInhaber() {
return inhaber;
}
public double getGuthaben() {
return guthaben;
}
public void einzahlen(double betrag) {
guthaben += betrag;
}
public void auszahlen(double betrag) {
guthaben -= betrag;
}
}
Using these classes, implement another class named Bank with the following properties:
The attribute named accounts is a directory of all
Account numbers and related accounts
(java.util.HashMap) and should be initialized in a default constructor of the class.
Write the addKonto method to add a new account of type Account, a getKonto method to query an account by its number, and a method called removeKonto that deletes an account with a specific number.
Implement a getGesamtguthaben method that returns the sum of the Balance(guthaben) of all bank accounts.
Write a containsKonto method that checks if an account with the given number exists in the bank and returns a corresponding Boolean value.
this is my code:
package Bank;
import java.util.HashMap;
import java.util.Map;
public class Bank {
private Map<String, Konto> konten;
public Bank() {
konten = new HashMap<String, Konto>();
}
public Konto addKonto(Konto konto) {
return konten.put(konto.getInhaber(), konto);
}
public String getKonto(String kontonr) {
if(konten.containsKey(kontonr)) {
return kontonr;
}
return null;
}
public Konto removeKonto(String kontonr) {
return konten.remove(kontonr);
}
public double getGesamtguthaben() {
for(double guthaben : konten) {
}
}
public boolean containsKonto(String kontonr) {
if(konten.containsKey(kontonr)) {
return true;
}else {
return false;
}
}
}
SO my question is how do i sum the balance of all Bank Accounts with a own method? And are the other methods correct? all help is appreciated
Use Map.entrySet to iterate over the entries.
double sum = 0;
for (Map.Entry<String, Konto> entrySet : konten.entrySet()) {
sum += entrySet.getValue().getGuthaben();
}
return sum;
Or using streams and Collectors.summarizingDouble
double sum = konten.entrySet()
.stream()
.collect(Collectors.summarizingDouble(entry -> entry.getValue().getGuthaben()))
.getSum();
Yes like user7 said. But instead of using the entrySet() you could also use the values() method.
double sum = konten.values()
.stream()
.collect(Collectors.summarizingDouble(konto-> konto.getGuthaben()))
.getSum();

Class created and Public Methods not going over to Test Method

I created a very simple cash register class and wanted to test it in a separate method. When I call the methods created in the class over from the test method, there is an error saying that a certain method is undefined in the class where it was created, when that is not the case. Can somebody please explain why I am getting this error? Thank you.
class:
/**
* A simulated cash register that tracks the item count and 3 the total
* amount due.
*/
public class CashRegister {
private int itemCount;
private double totalPrice;
public CashRegister() {
itemCount = 0;
totalPrice = 0;
}
public void addItem(double price) {
itemCount++;
totalPrice = totalPrice + price;
}
public double getTotal() {
return totalPrice;
}
public int getCount() {
return itemCount;
}
public void clear() {
itemCount = 0;
totalPrice = 0;
}
}
testing the class:
public class cashRegisterTester {
public static void main(String[] args) {
cashRegister register1 = new cashRegister();
register1.addItem(0.95);
register1.addItem(2.50);
System.out.println(register1.getCount());
System.out.println("Expected: 3");
System.out.printf("%.2f\n", register1.getTotal());
System.out.println("Expected: 5.40");
}
}
Get rid of the first public class cashRegister { line and the final }.
You have class within class:
public class cashRegister { /** * A simulated cash register that tracks the item count and 3 the total * amount due. */
public class CashRegister
Just delete the public class CashRegister and it should work for you.

Categories