I have one abstract class Account and one subclass SavingsAccount, but when I create SavingsAccount object it doesn't assign a number like 1001, 1002, 1003 and so on. Any idea why?
import java.util.ArrayList;
public abstract class Account {
private String accountType;
private static double balance = 0;
private static int accountId;
private static int accountNumberCounter = 1000;
private ArrayList<Account> accounts;
public Account(String acType, int acNumber){
accountType = acType;
accountNumberCounter ++;
accountId = accountNumberCounter;
}
public Account() {
accountNumberCounter++;
accountId = accountNumberCounter;
}
public void addAccounts(Account acc){
accounts.add(acc);
}
public void deposit(double amount){
balance += amount;
}
public abstract boolean withdraw(double value);
public String getAccountInfo(){
return "Account type: " + accountType + ", Account number: " + accountId;
}
public int getAccountNumber(){
return accountId;
}
public String getAccount(){
String accountInformation = "Account Number: : " + accountId + "\nAccount Type: " + accountType;
return accountInformation;
}
public void closeCurrentAccount() {
if (balance < 0) {
System.out.println("Your balance: " + balance + "Close your debt");
} else {
System.out.println("Ending balance: " + balance);
}
}
}
And this is SavingsAccount
public class SavingsAccount extends Account {
private static double balance = 0;
private static final double RATE = 1.0;
private static String accountType = "Savings Account";
private static int accountId;
public SavingsAccount(){
super();
}
public double getBalance(){
return balance;
}
public void deposit(double amount){
balance = balance + amount;
}
public boolean withdraw(double amount){
if (balance<= amount){
System.out.println("You have only" + amount + "left on your account.");
return false;
}
else{
balance -= amount;
System.out.println("You put:" + amount);
return true;
}
}
public static String getAccountType(){
return accountType;
}
public static double getRate(){
return RATE;
}
public static double calculateRate(){
return balance += (balance * RATE) / 100;
}
public String getAccount(){
String accountInformation = "Account Number: : " + accountId + "\nAccount Type: " + accountType +
"\nBalance: " + balance + "\nRate: " + RATE;
return accountInformation;
}
}
Maybe it's not needed but here is Customer class as well
import java.util.ArrayList;
public class Customer {
private String name;
private String surname;
private String personalNumber;
private ArrayList<Account> accounts;
public Customer(String customerName, String customerSurname, String customerPersonalNumber)
{
name = customerName;
surname = customerSurname;
personalNumber = customerPersonalNumber;
this.accounts = new ArrayList<Account>();
}
public Customer(){
}
public String getName(){
return name;
}
public String getSurname(){
return surname;
}
public String getPersonalNumber(){
return personalNumber;
}
public void setName(String aName){
name = aName;
}
public void setSurname(String aSurname){
surname = aSurname;
}
public void setPersonalNumber(String aPersonalNumber){
personalNumber = aPersonalNumber;
}
public void addAccounts(Account acc){
accounts.add(acc);
}
public String getCustomerInfo(){
return name + " " + surname + " " + personalNumber;
}
public int getFirstAccountNumber(){
return accounts.get(0).getAccountNumber();
}
public int getLastAccountNumber(){
return accounts.get(accounts.size()-1).getAccountNumber();
}
public ArrayList<Account> getAllAccounts(){
return accounts;
}
}
When I do some tests this unique number doesn't get assigned.
Is it something wrong with a constructor?
You marked accountId as static as well, so every instance of Account will acquire the same id, that is the latest you "generated".
Just mark accountId as a normal instance variable (i.e., remove static).
As a side note, re-declaring accountId in SavingsAccount breaks encapsulation and is, frankly, weird. You inherited getAccountNumber() from Account. Use that instead of accessing accountId directly. You're treating it as a read-only variable anyway.
I need to print out the content of my ArrayList however it doesn't print out correctly. More specifically it is the getAccountSaldo in CustomerRegister that is not returning the correct value (if I wanna print out for example a different account).
Here is my code:
Class Account
public class Account {
private Customer customer;
private String nbr;
private double saldo;
public void setNbr(String nbr){
this.nbr = nbr;
}
public String getNbr(){
return nbr;
}
public void setSaldo(double saldo){
this.saldo = saldo;
}
public double getSaldo(){
return saldo;
}
public void setCustomer(Customer customer){
this.customer = customer;
}
public Customer getCustomer(){
return customer;
}
public void withdraw(double amount){
saldo -= amount;
}
public void deposit(double amount){
saldo += amount;
}
}
Class Customer
public class Customer {
private String nbr;
private String namn;
private ArrayList<Account> accounts = new ArrayList<Account>();
public void setNbr(String nbr){
this.nbr = nbr;
}
public String getNbr(){
return nbr;
}
public void setNamn(String namn){
this.namn = namn;
}
public String getNamn(){
return namn;
}
public void setAccounts(ArrayList<Account> accounts){
this.accounts = accounts;
}
public ArrayList<Account> getAccounts(){
return accounts;
}
public void add(Account account){
accounts.add(account);
}
public Account find(String nbr){
for(Account a : accounts){
if(nbr == a.getNbr()){
return a;
}
}
return null;
}
}
Class CustomerRegister
public class CustomerRegister {
private ArrayList<Customer> customers = new ArrayList<Customer>();
public void setCustomers(ArrayList<Customer> customers){
this.customers = customers;
}
public ArrayList<Customer> getCustomers(){
return customers;
}
public void add(Customer k){
customers.add(k);
}
public Customer find(String nr){
for (Customer b : customers){
if (nr == b.getNbr()){
return b;
}
}
return null;
}
public ArrayList<Account> printAccounts(String customerNbr){
Customer l = find(customerNbr);
if (l != null){
return l.getAccounts();
}
return null;
}
// CAN'T SOLVE THIS
public Double getAccountSaldo(String customerNbr, String accountNbr) {
double balance = 0;
Customer custNbr = find(customerNbr);
// Shouldn't it be "Account acctNbr = find(accountNbr);" here?
// Problem is I can't access that method in this class...
if(custNbr != null){
for (Account x : printAccounts(customerNbr)) {
if (accountNbr == x.getNbr()) {
balance += x.getSaldo();
}
return balance;
}
}
return null;
}
}
Class demo:
public class Demo {
public static void main(String[] args){
CustomerRegister r1 = new CustomerRegister();
ArrayList<Account> listOfAccounts = new ArrayList<Account>();
ArrayList<Customer> listOfCustomers = new ArrayList<Customer>();
Customer c = new Customer();
c.setNbr("1");
c.setNamn("Adam Schinn");
Account a = new Account();
a.setNbr("Konto 1");
a.setSaldo(2200);
a.setCustomer(c);
Account b = new Account();
b.setNbr("Konto 2");
b.setSaldo(2000);
b.setCustomer(c);
listOfCustomers.add(c);
listOfAccounts.add(a);
listOfAccounts.add(b);
c.setAccounts(listOfAccounts);
r1.add(c);
r1.setCustomers(listOfCustomers);
for(Account temp : r1.printAccounts("1")){
System.out.println(temp.getNbr() + " Balance: " + temp.getSaldo() + "kr ");
}
for(Customer temp : r1.getCustomers()){
System.out.println("Nr: " + temp.getNbr() + " Namn: " + temp.getNamn());
}
// CAN'T SOLVE THIS
// If I write "Konto 2" instead of "Konto 1" it prints "0.0"
System.out.println(r1.getAccountSaldo("1", "Konto 1"));
}
}
Print out
Konto 1 Balance: 2200.0kr
Konto 2 Balance: 2000.0kr
Nr: 1 Namn: Adam Schinn
2200.0
You can't compare strings using == operator, this will not check equality for content instead it check the address of two strings.
Also the return statement was not at correct position.
I have made few changes to your function, have a try with that :
public Double getAccountSaldo(String customerNbr, String accountNbr) {
double balance = 0;
Customer custNbr = find(customerNbr);
// Shouldn't it be "Account acctNbr = find(accountNbr);" here?
// Problem is I can't access that method in this class...
if(custNbr != null){
for (Account x : printAccounts(customerNbr)) {
if (accountNbr.equals(x.getNbr())) {
balance += x.getSaldo();
}
}
}
return balance;
}
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);
I'm having a problem regarding a polymorphic invocation inside a loop.
I have an abstract class called Item that has two subclasses ClothingItem and SportItem and an abstract method called printBudgetGST(Items[] item) to return a string of an item with updated pricing which include tax.
Item Class :
public abstract class Item
{
private int code;
private double price;
private boolean isOnGST;
public Item()
{
}
public Item(int code,double price,boolean isOnGST)
{
this.code = code;
this.price = price;
this.isOnGST = isOnGST;
}
public void setGST(boolean isgst)
{
this.isOnGST = isgst;
}
public int getCode()
{
return code;
}
public boolean getIsOnGST()
{
return isOnGST;
}
public double getCurrentPrice()
{
return price;
}
public String toString() {
return "Item [code=" + code + ", price=" + price + ", isOnGST=" + isOnGST + "]";
}
public abstract String printBudgetGST(Item[] items);
}
ClothingItem class
public class ClothingItem extends Item
{
public ClothingItem(){
}
public ClothingItem(int code,double price,boolean isOnGST)
{
super(code,price,isOnGST);
}
#Override
public String printBudgetGST(Item[] item)
{
String stringitem ="";
for(int i=0;i<item.length;i++)
{
if(item[i].getIsOnGST()==true&&item[i].getCurrentPrice()<100.00)
{
double finalprice =(0.06*item[i].getCurrentPrice())+item[i].getCurrentPrice();
stringitem = stringitem + " " + "ClothingItem : " + item[i].getCode()+":"+"RM"+finalprice;
}
}
return stringitem;
}
}
SportsItem class:
public class SportsItem extends Item
{
public SportsItem(){
}
public SportsItem(int code,double price,boolean isOnGST)
{
super(code,price,isOnGST);
}
public String printBudgetGST(Item[] item)
{
String stringitem = "";
for(int i=0;i<item.length;i++)
{
if(item[i].getIsOnGST()==true &&item[i].getCurrentPrice()<150.00)
{
double finalprice =(0.06*item[i].getCurrentPrice())+item[i].getCurrentPrice();
stringitem = stringitem + "SportsItem : " + item[i].getCode()+":"+"RM"+finalprice;
}
}
return stringitem;
}
}
Test class :
public class Retail_Item
{
private Item[] itemList;
public Retail_Item()
{
itemList = new Item[10];
itemList[0] = new ClothingItem(10001,85,true);
itemList[1] = new ClothingItem(10002,150,false);
itemList[2] = new ClothingItem(10003,168,true);
itemList[3] = new ClothingItem(10004,43,true);
itemList[4] = new ClothingItem(10005,162,false);
itemList[5] = new SportsItem(10006,178,false);
itemList[6] = new SportsItem(10007,80,true);
itemList[7] = new SportsItem(10008,191,false);
itemList[8] = new SportsItem(10009,45,true);
itemList[9] = new SportsItem(10010,121,true);
}
public void printItem()
{
for(int i =0 ;i<itemList.length;i++)
{
if(itemList[i].getIsOnGST()==true && itemList[i].printBudgetGST(itemList).length()>0)
{
System.out.println(itemList[i].printBudgetGST(itemList));
}
}
}
}
public class TestRetailItem {
public static void main(String[] args)
{
Retail_Item ret = new Retail_Item();
ret.printItem();
}
}
OUTPUT :
The output should return a list of items which is on tax(GST) and with the updated pricing information like the example below
The problem is that you are passing to printBudgetGST the whole array of items and iterating over that array inside your implementations of printBudgetGST. Instead, you should remove that parameter and inside printBudgetGST you should simply call getCurrentPrice() and getCode() on this rather than on each item[i].
In addition, you are doing the check for maximum price (< 100 or < 150) inside the item subclasses but it's best to do this alongside the other checks in printItem. Because the max price depends on the subclass (SportsItem vs ClothinItem) I recommend you to create an abstract method boolean isOnBudget() in Item and implement accordingly in those two subclasses.
A fully fixed version of your code is
public abstract class Item {
private int code;
private double price;
private boolean isOnGST;
public Item()
{
}
public Item(int code,double price,boolean isOnGST)
{
this.code = code;
this.price = price;
this.isOnGST = isOnGST;
}
public void setGST(boolean isgst)
{
this.isOnGST = isgst;
}
public int getCode()
{
return code;
}
public boolean getIsOnGST()
{
return isOnGST;
}
public double getCurrentPrice()
{
return price;
}
public String toString() {
return "Item [code=" + code + ", price=" + price + ", isOnGST=" + isOnGST + "]";
}
public abstract String printBudgetGST();
public abstract boolean isOnBudget();
}
class ClothingItem extends Item {
public ClothingItem() {
}
public ClothingItem(int code, double price, boolean isOnGST) {
super(code, price, isOnGST);
}
#Override
public String printBudgetGST() {
String stringitem = "";
double finalprice = (0.06 * getCurrentPrice()) + getCurrentPrice();
stringitem = stringitem + " " + "ClothingItem : " + getCode() + ":" + "RM" + finalprice;
return stringitem;
}
#Override
public boolean isOnBudget() {
return getCurrentPrice() < 100.00;
}
}
class SportsItem extends Item {
public SportsItem() {
}
public SportsItem(int code, double price, boolean isOnGST) {
super(code, price, isOnGST);
}
public String printBudgetGST() {
String stringitem = "";
double finalprice = (0.06 * getCurrentPrice()) + getCurrentPrice();
stringitem = stringitem + "SportsItem : " + getCode() + ":" + "RM" + finalprice;
return stringitem;
}
#Override
public boolean isOnBudget() {
return getCurrentPrice() < 150.00;
}
}
class Retail_Item
{
private Item[] itemList;
public Retail_Item()
{
itemList = new Item[10];
itemList[0] = new ClothingItem(10001,85,true);
itemList[1] = new ClothingItem(10002,150,false);
itemList[2] = new ClothingItem(10003,168,true);
itemList[3] = new ClothingItem(10004,43,true);
itemList[4] = new ClothingItem(10005,162,false);
itemList[5] = new SportsItem(10006,178,false);
itemList[6] = new SportsItem(10007,80,true);
itemList[7] = new SportsItem(10008,191,false);
itemList[8] = new SportsItem(10009,45,true);
itemList[9] = new SportsItem(10010,121,true);
}
public void printItem() {
for(int i =0 ;i<itemList.length;i++) {
if(itemList[i].getIsOnGST()==true && itemList[i].printBudgetGST().length()>0 && itemList[i].isOnBudget())
{
System.out.println(itemList[i].printBudgetGST());
}
}
}
}
class TestRetailItem {
public static void main(String[] args) {
Retail_Item ret = new Retail_Item();
ret.printItem();
}
}
I am new to Java and I am working on a project that works with calculating prices with/without employee discounts. After reading the following code could someone explain to me how I might go about changing the parent class method outputs from the child class in order to get the correct outputs for my program?
Parent Class (I am NOT allowed to edit this):
public class GroceryBill {
private Employee clerk;
private List<Item> receipt;
private double total;
private double internalDiscount;
public GroceryBill(Employee clerk) {
this.clerk = clerk;
receipt = new ArrayList<Item>();
total = 0.0;
internalDiscount = 0.0;
}
public void add(Item i) {
receipt.add(i);
total += i.getPrice();
internalDiscount += i.getDiscount();
}
public double getTotal() {
return Math.rint(total * 100) / 100.0;
}
public Employee getClerk() {
return clerk;
}
public void printReceipt() {
System.out.println(this);
}
private String valueToString(double value) {
value = Math.rint(value * 100) / 100.0;
String result = "" + Math.abs(value);
if(result.indexOf(".") == result.length() - 2) {
result += "0";
}
result = "$" + result;
return result;
}
public String receiptToString() {
String build = "items:\n";
for(int i = 0; i < receipt.size(); i++) {
build += " " + receipt.get(i);
if(i != receipt.size() - 1) {
build += "\n";
}
}
return build;
}
public String toString() {
return receiptToString() + "\ntotal: " + valueToString(total);
}
public String discountToString() {
return receiptToString() + "\nsub-total: " + valueToString(total) + "\ndiscount: " + valueToString(internalDiscount) + "\ntotal: " + valueToString(total - internalDiscount);
}
public static class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public static class Item {
private String name;
private double price;
private double discount;
public Item(String name, double price, double discount) {
this.name = name;
this.price = price;
this.discount = discount;
}
public double getPrice() {
return price;
}
public double getDiscount() {
return discount;
}
private String valueToString(double value) {
String result = "" + Math.abs(value);
if(result.indexOf(".") == result.length() - 2) {
result += "0";
}
result = "$" + result;
return result;
}
public String toString() {
return name + " " + valueToString(price) + " (-" + valueToString(discount) + ")";
}
}
}
Here is my code:
public class DiscountBill extends GroceryBill
{
private int myDiscountCount;
private double myDiscountAmount;
private double myPrice;
public DiscountBill(Employee clerk, boolean preferred)
{
super(clerk);
String name = "";
double price = 0;
double discount = 0;
Object myItem = new Item(name, price, discount);
myPrice = ((GroceryBill.Item) myItem).getPrice() - ((GroceryBill.Item) myItem).getDiscount();
GroceryBill.Item myBill = new GroceryBill.Item(name, price, discount);
myDiscountAmount = myBill.getDiscount();
if (myDiscountAmount > 0 && preferred)
{
myDiscountCount++;
}
}
/*
public double getTotal()
{
Override goes here?
}
*/
public int getDiscountCount()
{
return myDiscountCount;
}
public double getDiscountAmount()
{
return myDiscountAmount;
}
public double getDiscountPercent()
{
return (myPrice / getDiscountCount()) * 100;
}
}
Lastly, here is the expected output:
P.S. Please let me know if I need to give more/less information and ways that I can clean up this post or make it easier to understand. If my question was too broad, please ask me what you don't understand about it and I'll try my best to tell you! Thank you!