java - 从不同的类调用方法到另一个类和方法

标签 java class methods compiler-errors bluej

我有两个类,一个叫做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/

相关文章:

java - 如何为 log4j2 配置 log4j2.properties 文件以拥有一个带有 2 个不同级别的附加程序的记录器?

java - 从其他类指向 UI 中的对象 - Android SDK

python - python `str()`函数是否调用类的 `__str__()`函数?

java - 从对象中获取数据; java

java - JPopupMenu 的 MenuItems 不响应更改...为什么?

java - Camel CXF JMS 连接问题

java - 将属性从一个类传递到另一个类+在java中实例化

java - "generic method""absolute value"java

objective-c - 类别中重写的方法是否始终优先于原始实现?

Java 字符串方法返回 Null?