Java compiling error on Eclipse - java

So I'm working on this program and I've created two classes, one class called CreditCard, the other called CreditCardTester.I'm using Eclipse IDE and I keep getting compiling errors such as "The method getBalance(double) in the type CreditCard is not applicable for the arguments ()". I'm not really sure on what I have to fix.
This is the first class called CreditCard:
public class CreditCard
{
private String accountNumber;
private double creditLimit;
private double balance;
public void CreditCard(String number, double limit)
{
accountNumber = number;
limit = creditLimit;
balance = 0;
}
public String getAccountNumber()
{
return accountNumber;
}
public double getCreditLimit()
{
return creditLimit;
}
public double getBalance(double theBalance)
{
return balance;
}
public double charge(double amount)
{
balance = balance + amount;
return balance;
}
This is the second class CreditCardTester:
public class CreditCardTester
{
public static void main(String[] args)
{
CreditCard card = CreditCard("1234-5678-9012-3456", 1000.00);
String formatString = "Credit Card [number = %s, bal = %.2f, limit = %.2f]\n";
System.out.printf(formatString, card.getAccountNumber(), card.getBalance(), card.getCreditLimit());
System.out.println("\nCharging $50.00 to credit card...\n");
card.charge(50.00);
System.out.printf(formatString, card.getAccountNumber(), card.getBalance(), card.getCreditLimit());
}

This is not a constructor, because you added void, making it a normal method:
public void CreditCard(String number, double limit)
Remove void:
public CreditCard(String number, double limit)
Also, one of the assignments in the method/constructor is backwards. You assigned the instance variable to the parameter.
limit = creditLimit;
Change it around:
creditLimit = limit;
You're missing "new" when creating a CreditCard:
CreditCard card = CreditCard("1234-5678-9012-3456", 1000.00);
Try
CreditCard card = new CreditCard("1234-5678-9012-3456", 1000.00);
You have an unused parameter on the getBalance method, and you call it without a parameter.
public double getBalance(double theBalance)
Remove it:
public double getBalance()

I think getBalance should not accept an argument in your class definition.
Use this in your CreditCard class:
public double getBalance()
{
return balance;
}

Related

Linking Credit Card and Debit Card classes to a Bank Account Class

I'm learning Java, and one of my assignments is to create Credit and Debit Cards classes so that you can create new cards linked to a new individual account when one is created. The credit card should store purchases, and when the user makes a payment (total or partial), substract the amount from the account (plus 3% interest). The debit card immediately substracts the purchase's amount from the account.
I have written everything and made it work, but only as nested classes within the Account class. Is there a way to have Account, Credit and Debit as three separate classes and make it so that every time that you create a new account, you can optionally create cards linked to each new individual account?
Disclaimer: I'm trimming some of the code because it's all in spanish so I don't have to translate it all (mainly booleans to check for positive amounts and stuff like that), but the code is still functional. Thanks a lot in advance!
package accounts;
public class Account {
protected static double balance;
protected static String accountNumber;
public Account() {
}
public Account(String accountNumber, double balance) {
Account.accountNumber = accountNumber;
Account.balance = balance;
}
public double getBalance() {
return balance;
}
public String getAccountNumber() {
return accountNumber;
}
public void deposit(double depositAmount) {
Account.balance += depositAmount;
}
public void extraction(double extractionAmount) {
Account.balance -= extractionAmount;
}
public void showBalance() {
System.out.println("Your current balance is: " + getBalance());
}
protected static class DebitCard {
private String userName;
private int cardNumber;
public DebitCard () {
}
public DebitCard (String userName, int cardNumber) {
this.userName = userName;
this.cardNumber = cardNumber;
}
public String getUserName() {
return userName;
}
public int getCardNumber() {
return cardNumber;
}
public void debitPurchase(double purchaseAmount) {
Account.balance -= purchaseAmount;
}
}
protected static class CreditCard {
private String userName;
private int cardNumber;
private double creditCardDebt;
private double limit;
public CreditCard () {
}
public CreditCard(String userName, int cardNumber, double limit) {
this.userName = userName;
this.cardNumber = cardNumber;
this.limit = limit;
}
public String getUserName() {
return userName;
}
public int getCardNumber() {
return cardNumber;
}
public double getLimit() {
return limit;
}
public double getCrediCardDebt() {
return creditCardDebt;
}
public void creditCardPurchase(double purchaseAmount) {
if (this.creditCardDebt + purchaseAmount > this.limit) {
Error notEnoughLimit = new Error("There's not enough limit to make this purchase");
throw notEnoughLimit ;
} else {
this.creditCardDebt += purchaseAmount + (purchaseAmount * 0.03);
this.limit -= purchaseAmount;
this.creditCardDebt += purchaseAmount + (purchaseAmount* 0.03);
this.limit -= purchaseAmount;
}
}
public void payCard(double payAmount) {
Account.balance -= payAmount;
this.creditCardDebt = this.creditCardDebt - payAmount;
}
}
}
Yes it is possible. But before you do that, you should solve the problem caused by declaring balance and accountNumber as static variables. By doing that, you have made every Account instance share one account number and one balance.
Those variables should also be private so that other classes can't access or change them directly.
Once you have fixed that, you should then change the constructors for Credit and Debit to take an instance of Account as a parameter. They store this in a private field, and then perform operations to add and remove money from the Account ... via operations on the Account object.

How do I use the transferTo() method to transfer money between accounts?

I am supposed to Add the following method to allow BankAccounts to transfer money to another BankAccount. Where would I add this method to make sure it works for all BankAccounts, including SavingsAccount and CheckingAccount?
The method im supposed to use is transferTo(BankAccount destinationAccount, int transferAmount)
public class BankAccount {
private String accountHolderName;
private String accountNumber;
private int balance;
public BankAccount(String accountHolder, String accountNumber) {
this.accountHolderName = accountHolder;
this.accountNumber = accountNumber;
this.balance = 0;
}
public BankAccount(String accountHolder, String accountNumber, int balance) {
this.accountHolderName = accountHolder;
this.accountNumber = accountNumber;
this.balance = balance;
}
public String getAccountHolderName() {
return accountHolderName;
}
public String getAccountNumber() {
return accountNumber;
}
public int getBalance() {
return balance;
}
// Update the balance by using the DollarAmount.Plus method
public int deposit(int amountToDeposit) {
balance = balance + amountToDeposit;
return balance;
}
// Update the balance by using the DollarAmount.Minus method
public int withdraw(int amountToWithdraw) {
balance = balance - amountToWithdraw;
return balance;
}
public int transferTo(BankAccount destinationAccount, int transferAmount) {
return balance;
}
}
Assumptions:
This is only an exercise and not a real application for a bank.
SavingsAccount and CheckingAccount are subclasses of BankAccount
The method transferTo can be implemented like the following:
public int transferTo(BankAccount destinationAccount, int transferAmount) {
this.balance -= transferAmount;
destinationAccount.deposit(transferAmount);
return balance;
}
In a real world application you need to ensure that this operation will be always atomic and thread-safe. Additionally, using int for the balance is strongly not recommended.

Inheritance java-bank account (java)

I am working on an inheritance bank account which has 5 classes.In one of the classes(InterestFreeDeposit) ,the account should be created with at least 10 $. How should I write the code of this part?
here is what I have done until now:
superClass:
import java.util.Scanner;
import java.io.FileReader;
public class Account {
private String owner;
private double balance;
private int accountNumber;
private double interestRate;
public Account( String owner,double balance, int accountNumber , double interestRate){
this.balance=balance;
this.owner=owner;
this.accountNumber=accountNumber;
this.interestRate=interestRate;
}
public void deposit(double amount) {
if(amount>0) {
this.balance+=amount;
}
}
public void withdraw(double amount) {
if(amount>0 && balance>=amount) {
this.balance-=amount;
}
}
public double getBalance() {
return balance;
}
public void setBalance(double amount) {
this.balance = amount;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
public double getInterestRate() {
return interestRate;
}
public double setInterestRate(double interestRate) {
//System.out.println("Enter the period(month):");
return this.balance +=balance * interestRate/100;
}
subClass(InterestFrreClass):
public class InterestFreeDeposit extends Account {
public InterestFreeDeposit(String owner, double balance, int accountNumber, double interestRate) {
super(owner, balance, accountNumber, interestRate);
// TODO Auto-generated constructor stub
}
public void interest() {
super.setInterestRate(0.0) ;
}
}
You need to add the check when the value is set, which in this case happens in the constructor of InterestFreeDeposit. The question is how you want to react when the value is below 10. You could throw an IllegalArgumentException:
public InterestFreeDeposit(String owner, double balance, int accountNumber, double interestRate) {
super(owner, balance, accountNumber, interestRate);
if(balance < 10){
throw new IllegalArgumentException("balance must be at least 10");
}
}
The problem with this approach is that IllegalArgumentException is an unchecked exception, meaning that the caller of the constructor is not forced to deal with it if it is thrown.
You can use a ternary operator in your subclass constuctor to default to a 10.0 minimum value:
public class InterestFreeDeposit extends Account {
public InterestFreeDeposit(String owner, double balance, int accountNumber, double interestRate) {
super(owner, balance < 10.0 ? 10.0 : balance, accountNumber, interestRate);
}
}
A ternary operator can be seen as an inline if. So you have following structure:
condition ? condition is true : condition is false
In the above snippet it just checks if the provided balance is below the 10.0. if it is it just sets it to 10, else it is passed along:
balance < 10.0 ? 10.0 : balance

Why are my constructors recognized as methods?

I am working on a program to hold bank accounts as objects. The accounts have an interest rate, balance, ID, and date created data to go along. In what I have made, the default balance, id, and interest is 0 from what I understand. The interest rate is undefined by default. The book I am learning form shows that a no-arg constructor is done with "Circle() { }".I used "account() { }" in the account class. When I run the program in jGRASP, I get error "invalid method declaration; return type required" for both of my constructors. It is recognizing what I intend to be constructors as methods. What do I need to understand so I can make my constructors not be recognized as methods?
When running the first constructor, I understand we create an Account object called account with the default values. When we run the second constructor, we are changing the values of the account object to something with specified
public class Bank{
public static void main(String[] args){
Account account = new Account(1122, 20000);
account.setAnnualInterestRate(4.5);
account.withdraw(2500);
account.deposit(3000);
System.out.println("Balance is " + account.getBalance());
System.out.println("Monthly interest is " + account.getMonthlyInterest());
System.out.println("This account was created at " + account.getDateCreated());
}
}
class Account {
private int id = 0;
private double balance = 0;
private double annualInterestRate = 0;
private String dateCreated;
account(){
}
account(int newID, double newBalance){
id = newID;
balance = newBalance;
}
//accessor for ID
public int getID(){
return id;
}
//acessor for balance
public double getBalance(){
return balance;
}
//accessor for interest rate
public double getAnnualInterest(){
return annualInterestRate;
}
//mutator for ID
public void setID(int IDset){
id = IDset;
}
//mutator for balance
public void setBalance(int BalanceSet){
balance = BalanceSet;
}
//mutator for annual interest
public void setAnnualInterestRate(double InterestSet){
annualInterestRate = InterestSet;
}
//accessor for date created
public String getDateCreated(){
return dateCreated;
}
//method that converts annual interest into monthly interest and returns the value
public double getMonthlyInterest(){
double x = annualInterestRate / 12;
return x;
}
//method that witdraws from account
public double withdraw(double w){
balance -= w;
return balance;
}
//method that deposits into account
public double deposite(double d){
balance += d;
return balance;
}
}
Constructor names must match the class names in a case sensitive way. In the Account class, change
account(){
to
Account(){
and likewise for your other constructor.
You need to capitalize your a in both constructors. Java is case sensitive.
Account(){
}
Account(int newID, double newBalance){
id = newID;
balance = newBalance;
}
Otherwise, Java sees this as a method with no return type. Remember, a constructor does not have or needs a return type.
Constructors should be camelized(as a convention, same with the class name) and it return only the type of itself
see my example :)
Account() {
return;
}

cannot make a static reference to the non-static field

I apologize ahead of time if this code isn't formatted correctly, trying to paste instead of retyping each line. If it isn't right, can someone tell me an easy way to paste multiple lines of code at once?
My main question is that I keep getting an error message stating: Cannot make a static reference to the non-static field balance.
I have tried making the methods static, with no result, and making the main method non-static by removing "static" from the header, but then I get the message: java.lang.NoSuchMethodError: main Exception in thread "main"
Does anyone have any ideas? Any help is appreciated.
public class Account {
public static void main(String[] args) {
Account account = new Account(1122, 20000, 4.5);
account.withdraw(balance, 2500);
account.deposit(balance, 3000);
System.out.println("Balance is " + account.getBalance());
System.out.println("Monthly interest is " + (account.getAnnualInterestRate()/12));
System.out.println("The account was created " + account.getDateCreated());
}
private int id = 0;
private double balance = 0;
private double annualInterestRate = 0;
public java.util.Date dateCreated;
public Account() {
}
public Account(int id, double balance, double annualInterestRate) {
this.id = id;
this.balance = balance;
this.annualInterestRate = annualInterestRate;
}
public void setId(int i) {
id = i;
}
public int getID() {
return id;
}
public void setBalance(double b){
balance = b;
}
public double getBalance() {
return balance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double interest) {
annualInterestRate = interest;
}
public java.util.Date getDateCreated() {
return this.dateCreated;
}
public void setDateCreated(java.util.Date dateCreated) {
this.dateCreated = dateCreated;
}
public static double withdraw(double balance, double withdrawAmount) {
double newBalance = balance - withdrawAmount;
return newBalance;
}
public static double deposit(double balance, double depositAmount) {
double newBalance = balance + depositAmount;
return newBalance;
}
}
main is a static method. It cannot refer to balance, which is an attribute (non-static variable). balance has meaning only when it is referred through an object reference (such as myAccount.balance or yourAccount.balance). But it doesn't have any meaning when it is referred through class (such as Account.balance (whose balance is that?))
I made some changes to your code so that it compiles.
public static void main(String[] args) {
Account account = new Account(1122, 20000, 4.5);
account.withdraw(2500);
account.deposit(3000);
and:
public void withdraw(double withdrawAmount) {
balance -= withdrawAmount;
}
public void deposit(double depositAmount) {
balance += depositAmount;
}
the lines
account.withdraw(balance, 2500);
account.deposit(balance, 3000);
you might want to make withdraw and deposit non-static and let it modify the balance
public void withdraw(double withdrawAmount) {
balance = balance - withdrawAmount;
}
public void deposit(double depositAmount) {
balance = balance + depositAmount;
}
and remove the balance parameter from the call
You are trying to access non static field directly from static method which is not legal in java. balance is a non static field, so either access it using object reference or make it static.
The static calls to withdraw and deposit are your problem.
account.withdraw(balance, 2500);
This line can't work , since "balance" is an instance variable of Account. The code doesn't make much sense anyway, wouldn't withdraw/deposit be encapsulated inside the Account object itself? so the withdraw should be more like
public void withdraw(double withdrawAmount)
{
balance -= withdrawAmount;
}
Of course depending on your problem you could do additional validation here to prevent negative balance etc.
Just write:
private static double balance = 0;
and you could also write those like that:
private static int id = 0;
private static double annualInterestRate = 0;
public static java.util.Date dateCreated;
To access instance variables it is a must to create an object, these are not available in the memory, before instantiation.
Therefore, you cannot make static reference to non-static fields(variables) in Java. If you still, try to do so a compile time error is generated saying “non-static variable math cannot be referenced from a static context”.
you can keep your withdraw and deposit methods static if you want however you'd have to write it like the code below.
sb = starting balance and eB = ending balance.
Account account = new Account(1122, 20000, 4.5);
double sB = Account.withdraw(account.getBalance(), 2500);
double eB = Account.deposit(sB, 3000);
System.out.println("Balance is " + eB);
System.out.println("Monthly interest is " + (account.getAnnualInterestRate()/12));
account.setDateCreated(new Date());
System.out.println("The account was created " + account.getDateCreated());

Categories