调用一个方法从一个不同的类到另一个类&方法 [英] Calling a method from a different class to another class & method
问题描述
我有两个类,一个叫Driver,另一个叫BankAccount。在Driver中有一个称为Driver的方法,在BankAccount中有一个称为Deposit的方法。我收到一个错误,说:当我尝试从我的驱动程序方法调用BankAccount.Deposit时,非静态方法Deposit()不能从静态上下文引用。
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);
}
}
这里是BankAccount方法
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;
}
}
推荐答案
我不明白为什么你写了这样的代码。
I don't understand why you have written your code like this.
java中的方法名应以小写字母开头,如
,而不是存款
。
Method name in java should start with a small letter like deposit
and not Deposit
.
BankAccount
是一个类, Deposit
是一个非静态方法。
BankAccount
is a class and Deposit
is a non-static method in it.
因此,对于使用存款
方法,您必须先创建一个 BankAccount
这样的类:
So for using Deposit
method you must first create an object/instance of your BankAccount
class like this :
BankAccount b =new BankAccount();
然后使用任何使用该对象引用的方法:
And then use any method using that object reference :
b.Deposit();
b.Withdraw();
您应该这样写:
if( choice == 1)
{
BankAccount b = new BankAccount();
b.Deposit();
}
撤回时需要执行的操作
else if(choice == 2)
{
BankAccount b = new BankAccount();
b.Withdrawl();
Driver.Driver = new Driver();
}
这篇关于调用一个方法从一个不同的类到另一个类&方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!