I am having a rather trivial problem creating my own exception class. I have extending it and am trying to recieve a double in the constructor but I keep getting errors.
Error inside of bankaccount #withdraw "incompatible types: InsufficientFundsException cannot be converted to throwable"
Exception class:
public class InsufficientFundsException extends RuntimeException {
private double shortFall;
public InsufficientFundsException(double a) {
super("Insufficient funds");
shortFall = a;
}
public double getAmount() { return shortFall; }
}
Bank Account class:
public class BankAccount {
private int accountNumber;
private double balance;
// Class constructor
public BankAccount(int account) {
accountNumber = account;
balance = 0.0;
}
public int getAccountNumber() {
return accountNumber;
}
public double getBalance()
{
return balance;
}
public void deposit(double b) {
balance += b;
}
public void withdraw(double w) throws InsufficientFundsException {
double difference;
if(w > balance) {
difference = w - balance;
} else {
balance -= w;
}
}
I would like to withdraw money unless the withdraw is greater than the current balance. In which case I want to throw an exception. I also tried to throw and exception inside of the if but I get:
constructor InsufficientFundsException in class InsufficientFundsException cannot be applied to gived types;
required: no arguments
found: double
reason: actual and formal argument lists differ in length
public void withdraw(double w) {
double difference;
if(w > balance) {
difference = w - balance;
Exception ex = new InsufficientFundsException(difference);
} else {
balance -= w;
}
}
I only have the one constructor though. Any advice or help is appreciated.
Have you tried...
throw new InsufficientFundsException(difference);
in place of
Exception ex = new InsufficientFundsException(difference);
That's generally how exceptions are thrown.
Updated code snippet...
public void withdraw(double w) throws InsufficientFundsException {
double difference;
if(w > balance) {
difference = w - balance;
throw new InsufficientFundsException(difference);
} else {
balance -= w;
}
}
Ran with...
public static void main(String[] args){
BankAccount account = new BankAccount(1);
account.withdraw(5.0);
}
Got....
Exception in thread "main" com.misc.help.InsufficientFundsException: Insufficient funds
at com.misc.help.BankAccount.withdraw(BankAccount.java:32)
at com.misc.help.BankAccount.main(BankAccount.java:40)
Related
public class Acc{
private double balance;
public Account()
{
balance = 5;
}
public Acc(double sBalance)
{
balance = sBalance;
}
public void depos(double amount)
{
balance = balance + amount;
}
public void withd(double amount)
{
balance = balance - amount;
if (withd>balance){
System.out.println("Error");
}
}
public double gBalance()
{
return balance;
}
}
Main:
public class Main{
public static void main(String[] args){
Acc newBank = new Acc(50);
newBank.withd(20);
newBank.depos(5);
System.out.println(newBank.gBalance());
}
}
Basically I wanted to create a function to withdraw and deposit a value from stored in balance, where $5 is added to every new account created. It seems to work, however I wanted to extend and make it so withdrawing more than the balance amount would give an error and not take away from the balance
First, there are inconsistencies in the code you provided, which makes it impossible to compile:
The first constructor is public Account() while the class name is Acc
As pointed out by #Andy Turner, you are using the method name withd in the condition. It should rather be amount > balance.
If I understand what you are trying to do, the withdraw method should be:
public void withd(double amount)
{
if (amount > balance) {
System.out.println("Error");
} else {
balance = balance - amount;
}
}
where you check if the balance has enough money before performing the withdraw.
i have a problem on my program. and my problem is that i cannot minus my withdrawal from my deposit value.
code below:
public static void main(String[] args) {
double cash;
boolean more = true;
Deposite dep = new Deposite();
Withdraw with = new Withdraw();
while (more) {
cash = Double.parseDouble(JOptionPane.showInputDialog("Cash Deposite"));
dep.Deposite(cash);
dep.print();
int con = JOptionPane.YES_NO_OPTION;
int con1 = JOptionPane.showConfirmDialog(null, "Do you want more Deposites?","DEPOSITORY",con);
if (con1 == 1) {
int con3 = JOptionPane.showConfirmDialog(null, "Withdraw now?","WITHDRAWAL",con);
if (con3 == 0) {
cash = Double.parseDouble(JOptionPane.showInputDialog("Cash Withdraw"));
with.Withdraw(cash);
with.print();
System.out.println("Thanks");
}
}
}
}
and this is my subclass that i have made for its functions
public class Deposite {
private double depcash;
public double Deposite(double cash){
depcash += cash;
return this.depcash;
}
void print(){
System.out.printf("Your deposite is $%5.2f",depcash);
System.out.println(" ");
}
}
and this is for my withdrawal class. i inherit it. but i still dont know how it works.
code below :
public class Withdraw extends Deposite {
double cash;
public double Withdraw(double withdraw){
super.Deposite(withdraw);
cash -=withdraw;
return cash;
}
void print (){
System.out.printf("You Cash Balance now is $%5.2f",cash);
System.out.println(" ");
}
}
First of all, never name your methods like object constructors
public double Deposite(double cash).
Secondly, why would your Withdraw class extend Deposite? Is there any reason for this?
That is how I would implement some banking logic:
Bank bank = new Bank();
Account account = new Account(123.50);
bank.execute(account, new Deposit(), 1);
bank.execute(account, new Withdraw(), 13.50);
private static interface Operation {
double apply(Account account, double value);
}
private static class Deposit implements Operation {
#Override
public double apply(Account account, double value) {
return account.getMoney() - value;
}
}
private static class Withdraw implements Operation {
#Override
public double apply(Account account, double value) {
return account.getMoney() + value;
}
}
private static class Account {
private final double money;
public Account(double money) {
this.money = money;
}
public double getMoney() {
return money;
}
}
private static class Bank {
public void execute(Account account, Operation operation, double amount) {
operation.apply(account, amount);
}
}
Your program have some basic problem here is the code:::
You should have made the single account for deposit and withdraw. That was your basic mistake.
import javax.swing.JOptionPane;
public class Bank {
public static double totalCash = 0;
public static void main(String[] args) {
boolean more = true;
Deposite dep = new Deposite();
Withdraw with = new Withdraw();
while (more) {
double cash = Double.parseDouble(JOptionPane.showInputDialog("Cash Deposite"));
dep.depositeCash(cash);
dep.print();
int con = JOptionPane.YES_NO_OPTION;
int con1 = JOptionPane.showConfirmDialog(null, "Do you want more Deposites?", "DEPOSITORY", con);
if (con1 == 1) {
int con3 = JOptionPane.showConfirmDialog(null, "Withdraw now?", "WITHDRAWAL", con);
if (con3 == 0) {
cash = Double.parseDouble(JOptionPane.showInputDialog("Cash Withdraw"));
with.withdrawCash(cash);
with.print();
System.out.println("Thanks");
more = false;
}
}
}
}
}
class Withdraw {
public double withdrawCash(double withdraw) {
Bank.totalCash -= withdraw;
return Bank.totalCash;
}
void print() {
System.out.printf("You Cash Balance now is $%5.2f", Bank.totalCash);
System.out.println(" ");
}
}
class Deposite {
public double depositeCash(double cash) {
Bank.totalCash += cash;
System.out.println(Bank.totalCash);
return Bank.totalCash;
}
void print() {
System.out.printf("Your deposite is :" + Bank.totalCash);
System.out.println(" ");
}
}
When you do
Deposite dep = new Deposite();
Withdraw with = new Withdraw();
it creates two different instances. One of Deposite and one of Withdraw.
You assume that both instances share the same double cash , but they don't.
If you want to start with something simple you could do something like :
import javax.swing.JOptionPane;
public class Cash {
private double depcash;
public double deposite(double cash){ //stick to java naming conventions
depcash += cash;
return depcash;
}
public double withdraw(double withdraw){
return deposite(- withdraw);
}
void print(){
//wrong - System.out.printf("Your deposite is $%5.2f",depcash);
System.out.printf("Your cash balance is $%5.2f",depcash);
System.out.println(" ");
}
public static void main(String[] args) {
double sum;
boolean more = true;
Cash cash = new Cash();
while (more) { //how do you stop ? what makes more false ?
sum = Double.parseDouble(JOptionPane.showInputDialog("Cash deposite"));
cash.deposite(sum);
cash.print();
int con = JOptionPane.YES_NO_OPTION;
int con1 = JOptionPane.showConfirmDialog(null, "Do you want more Deposites?","DEPOSITORY",con);
if (con1 == 1) {
int con3 = JOptionPane.showConfirmDialog(null, "Withdraw now?","WITHDRAWAL",con);
if (con3 == 0) {
sum = Double.parseDouble(JOptionPane.showInputDialog("Cash Withdraw"));
cash.withdraw(sum);
cash.print();
System.out.println("Thanks");
}
}
}
}
}
I have been provided with a Superclass called Account with constructor to initialize the balance, and methods to deposit, and withdraw balance, with the balance being declared private. (I cannot add or change any methods or variables in this class at all)
Then, I created a subclass called SavingsAccount with a constructor that accepts a initial balance. If the initial balance is negative, then the account should be initialized with a balance of 0. Also, it contains two over-ridden methods, deposit and withdraw, which checks the amount being deposited and withdrawn to see if it is possible or not. Here's the code that I've been provided (Account) and that I've written (SavingsAccount).
I tried calling the super() inside a if-else conditional, but Java gives an error that super()call has to be the first line of the constructor. So, how do I get around this? Also, since I don't have a setBalance() method in the provided Account class, how can I set the balance from my deposit and withdraw methods in my SavingsAccount class?
Account.Java (Provided for testing, and cannot modify)
public class Account
{
private double balance;
// Constructor to initialise balance
public Account( double amount )
{
balance = amount;
}
// Overloaded constructor for empty balance
public Account()
{
this(0.0);
}
public void deposit( double amount )
{
balance += amount;
}
public void withdraw( double amount )
{
balance -= amount;
}
public double getBalance()
{
return balance;
}
}
SavingsAccount.java (Written by me)
public class SavingsAccount extends Account
{
private int overDraftCount = 0;
public SafeAccount(double initial_balance)
{
if(initial_balance <0)
{
super(0.00);
}
else
{
super(initial_balance);
}
}
#Override
public void deposit(double amount)
{
if(amount < 0)
{
??? = getBalance();
}
else
{
??? = getBalance()+ amount;
}
}
#Override
public void withdraw(double amount)
{
if(amount < getBalance())
{
overDraftCount++;
??? = getBalance();
}
else
{
??? = getBalance() - amount;
}
}
public int overdraftAttempts()
{
return overDraftCount;
}
}
You can change your constructor to use the ternary operator:
public SafeAccount(double initial_balance) {
super(initial_balance < 0 ? 0.00 : initial_balance);
}
Regarding your second point you will have to use the existing methods to withdraw or deposit savings from/to the account like this:
#Override
public void deposit(double amount) {
if(amount > 0) {
super.deposit(amount);
}
}
In this case, it can simply be solved using
public SafeAccount(double initialBalance) {
super(initialBalance < 0 ? 0.0 : initialBalance));
}
You could also call a static method returning the correct initial balance. Or you could use a factory method instead of a constructor:
private SafeAccount(double initialBalance) {
super(initialBalance);
}
public static SafeAccount createSafeAccount(double initialBalance) {
if (initialBalance < 0) {
return new SafeAccount(0.0);
}
else {
return new SafeAccount(initialBalance);
}
}
Note that ignoring the argument value that way is most of the time a bad idea. Passing a negative initial balance doesn't make sense, and is thus the sign of a bug. It should thus be signalled by throwing an exception, instead of transforming it to 0.0 and hide the bug, probably thus causing a new bug, even more nasty and harder to diagnose.
Regarding your second question, I don't really see where the problem is. You just need to delegate to the super method:
#Override
public void deposit(double amount) {
if (amount < 0) {
throw new IllegalArgumentException("amount should be positive");
}
else {
super.deposit(amount);
}
}
If I correctly understood, you want to make an Account that can't be negative.
So for the constructor, you just have to use a ternary operator:
public SafeAccount(double initialBalance) {
super(initialBalance < 0 ? 0 : initialBalance);
}
And for deposit/withdraw, you can call Account's method using super as well:
#Override
public void deposit(double amount) {
if (amount > 0) {
super.deposit(amount);
}
}
#Override
public void withdraw(double amount) {
if (amount > getBalance()) {
overDraftCount++;
// if you want to set to 0.00
super.withdraw(getBalance());
} else {
super.withdraw(amount);
}
}
So, your final class should be like this:
public class SafeAccount extends Account {
private int overDraftCount = 0;
public SafeAccount(double initialBalance) {
super(initialBalance < 0 ? 0 : initialBalance);
}
#Override
public void deposit(double amount) {
if (amount > 0) {
super.deposit(amount);
}
}
#Override
public void withdraw(double amount) {
if (amount > getBalance()) {
overDraftCount++;
// if you want to set to 0.00
super.withdraw(getBalance());
} else {
super.withdraw(amount);
}
}
public int overdraftAttempts() {
return overDraftCount;
}
}
Note: your code doesn't respect java code conventions, maybe you should take a look at them (google java code conventions, you'll find).
Your constructor of SavingsAccount can't work, because the first line of your own constructor must be the super-call, otherwise you will get a compile error. You can achieve your desired result by do something like this:
public SavingsAccount(double initial_balance) {
super(getAdjustedInitialBalance(initial_balance));
}
private static double getAdjustedInitialBalance(double val) {
return val < 0 ? 0 : val;
}
Of course the trinary operator can be placed inside the super-call directly as parameter but I find my way more readable since it's explaining the logic by meaningful methodnames.
The other methods can just call each other in case of negative values:
public void withdraw(double amount) {
if (amount < 0) {
deposit(-amount);
return;
}
if (amount < getBalance()) {
overDraftCount++;
return;
}
super.withdraw(amount);
}
public void deposit(double amount) {
if (amount < 0) {
withdraw(-amount);
return;
}
super.deposit(amount);
}
So, the answer to your original question is "you can't" (well technically there is a way but you don't do that until you really have to, so I won't show it to you ;-) " and you shouldn't". You use the methods that are publicly available and call them.
Hope that helps with your homework (at least it looks like one)
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)`
}
}
I am writing a program that keeps track of different transactions
done over time. I have a main class, and also another class named
CheckingAccount.java.
I have a main class formatted this way.
public class Main
{
public static void main (String[] args)
{
CheckingAccount c = new CheckingAccount(bal);
--line of code---
--line of code---
--line of code---
}
public static int getTransCode()
{
--line of code---
}
public static double getTransAmt()
{
--line of code---
}
public static void processCheck(double trAm, int tCode, boolean monthCh)
{
double curCharge=0.15;
CheckingAccount.setBalance(trAm,tCode,curCharge,monthCh);
CheckingAccount.setServiceCharge(curCharge);
}
public static void processDeposit(double trAm, int tCode, boolean monthCh)
{
double curCharge=0.10;
CheckingAccount.setBalance(trAm,tCode,curCharge,monthCh);
CheckingAccount.setServiceCharge(curCharge);
}
}
This is my CheckingAccount.java
public class CheckingAccount
{
private double balance;
private double totalServiceCharge;
public CheckingAccount(double initialBalance)
{
balance = initialBalance;
totalServiceCharge = totalServiceCharge;
}
public double getBalance()
{
return balance;
}
public void setBalance(double tAm, int Code, double charge, boolean mChrg)
{
if(tCode == 1)
balance = (balance - tAm) - charge;
else //if(tCode == 2)
balance = (balance + tAm) - charge;
}
public double getServiceCharge()
{
return totalServiceCharge;
}
public void setServiceCharge(double currentServiceCharge)
{
totalServiceCharge = totalServiceCharge+currentServiceCharge;
}
}
So the lines I can't get to work are CheckingAccount.setBalance() and CheckingAccount.setServiceCharge() inside the functions on my main class. What I'm trying to do is to call the the methods I created (setBalance, and setServiceCharge) in my class, from functions that I created on my main class (processCheck, and processDeposit).
But I cannot get it to run, I keep running with these error messages.
non-static method setBalance(double,int,double,boolean) cannot be referenced from a static context
CheckingAccount.setBalance(trAm,tCode,curCharge,monthCh);
You are calling your setBalance through classname which is wrong.... setBalance() method is non-static, so it is defined to specific instance of the class, not for a class..
**CheckingAccount.setBalance(trAm,tCode,curCharge,monthCh);
CheckingAccount.setServiceCharge(curCharge);**
You need to create an instance of CheckingAccount to call the method..
Secondly, in your constructor of CheckingAccount class, you haven't passed any argument for totalService, but you are setting one with an unknown variable..
You will get a compiler error there..
Either you need to initialize your totalServiceCharge with a fixed value or, you can pass it as an argument from main.. And change your constructor as below..
public CheckingAccount(double initialBalance, ** double totalServiceCharge)
{
balance = initialBalance;
this.totalServiceCharge = totalServiceCharge;
}
Then from main, call it like this: -
CheckingAccount ca = new CheckingAccount(bal, totalServiceCharge);
One of the possible solution is:
You need to create object for CheckingAccount before calling method.
Example:
public static void processDeposit(double trAm, int tCode, boolean monthCh)
{
double curCharge=0.10;
CheckingAccount ca = new CheckingAccount();
ca.setBalance(trAm,tCode,curCharge,monthCh);
ca.setServiceCharge(curCharge);**
}
Another way is, change setBalance method as static method.
public static void setBalance(double tAm, int Code, double charge, boolean mChrg)
{
if(tCode == 1)
balance = (balance - tAm) - charge;
else //if(tCode == 2)
balance = (balance + tAm) - charge;
}
I think first approach makes more sense than second approach.
CheckingAccount.setBalance and CheckingAccount.setServiceCharge are not static methods (and in this context, they shouldn't be).
You need to pass a reference of the account to your methods...
public static void processCheck(CheckingAccount ca, double trAm, int tCode, boolean monthCh)
{
double curCharge=0.15;
ca.setBalance(trAm,tCode,curCharge,monthCh);
ca.setServiceCharge(curCharge);**
}
public static void processDeposit(CheckingAccount ca, double trAm, int tCode, boolean monthCh)
{
double curCharge=0.10;
ca.setBalance(trAm,tCode,curCharge,monthCh);
ca.setServiceCharge(curCharge);
}
The you would be able to do something like...
public static void main (String[] args)
{
CheckingAccount c = new CheckingAccount(bal);
processCheck(ca, 100.0, 1, false);
}