我有两个类,一个叫做Driver,另一个叫做BankAccount。在Driver中,有一个称为Driver的方法,在BankAccount中有一个称为Deposit的方法。当我尝试从Driver方法调用BankAccount.Deposit时,出现一个错误,指出“无法从静态上下文引用非静态方法Deposit()”。
关于如何对这些代码行进行操作的任何建议。
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方法
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;
}
}
最佳答案
我不明白为什么您要这样编写代码。
Java中的方法名称应以小写字母开头,例如deposit
而不是Deposit
。BankAccount
是一个类,而Deposit
是其中的非静态方法。
因此,对于使用Deposit
方法,您必须首先创建BankAccount
类的对象/实例,如下所示:
BankAccount b =new BankAccount();
然后使用任何使用该对象引用的方法:
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();
}
关于java - 从不同的类调用方法到另一个类和方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13965441/