I have two classes, one called Driver and another called BankAccount. In Driver there is a method called Driver, and in BankAccount a method called Deposit. I'm getting an error that says, "non-static method Deposit() cannot be referenced from a static context" when I try to call BankAccount.Deposit from my Driver method.
Any advice on what I should do to these lines of code to make it run.
import javax.swing.JOptionPane;
public class Driver
{
int choice;
String number;
//public Driver()
public Driver()
{
String number = JOptionPane.showInputDialog("1. Deposit 2. Withdraw 3. Balance 4. Change name 5. Exit");
int choice = Integer.parseInt(number);
do
{
if( choice == 1)
{
BankAccount.Deposit() = new Deposit();
Driver.Driver = new Driver();
}else if(choice == 2)
{
BankAccount.Withdrawl = new Withdrawl();
Driver.Driver = new Driver();
}else if(choice == 3)
{
BankAccount.getBalance = new getBalance();
JOptionPane.showDialog(balance);
Driver.Driver = new Driver();
}else if(choice == 4)
{
name = JOptionPane.showInputDialog(" Please enter a name");
Driver.Driver = new Driver();
}else if(choice ==5)
{
JOptionPane.showDialog("Goodbye" + name);
}
}while( choice >= 1 && choice <= 5);
}
}
here is the BankAccount Method
import javax.swing.JOptionPane;
public class BankAccount
{
double balance = 400;
double deposit;
double withdraw;
double Interest = 1.05;
String name;
String accountNumber;
public BankAccount()
{
name = null;
accountNumber = null;
balance = 0;
}
public double Deposit()
{
String input = JOptionPane.showInputDialog("How much would you like to deposit?");
deposit = Integer.parseInt(input);
if (deposit < 10000)
{
balance = (deposit + balance);
}
return balance;
}
}
This statement:
makes no sense. First,
Deposit()
is an instance method ofBankAccount
. It only makes sense to call it for a particular instance ofBankAccount
. That's what the compiler is complaining about.Beyond that, there's the problem that
Deposit()
returns anint
value, which is not something that can appear on the left side of an assignment statement. Also, you don't mention any class namedDeposit
, so I don't know whatnew Deposit()
is supposed to be.You seem to have similar problems further on in your code. For instance, the next statement:
is utter nonsense—there is no field
Driver.Driver
.I recommend that you read the tutorial Understanding Instance and Class Members.
a working version of your 'intention' :
I don't understand why you have written your code like this.
Method name in java should start with a small letter like
deposit
and notDeposit
.BankAccount
is a class andDeposit
is a non-static method in it.So for using
Deposit
method you must first create an object/instance of yourBankAccount
class like this :And then use any method using that object reference :
You should write it like this :
Same you need to do for withdraw and other