【问题标题】:Updating information by calling methods from another class通过调用另一个类的方法来更新信息
【发布时间】:2016-05-03 15:46:28
【问题描述】:

在 AccountApplet 类的 actionPerformed 方法中,我试图让 setBalance 在调用时更新余额,我不知道为什么,但我调用它进行存款的方式并没有更新余额。这是它的正确输出应该是什么样子。 请注意,当我运行我的时,1000 保持 1000,而不是输入的余额 + 存款

我还收到以下错误

AccountApplet2.java:155: error: non-static method getId() cannot be referenced from a static context
    aitf.setText("" + Account.getId());
                             ^
AccountApplet2.java:156: error: non-static method getBalance() cannot be referenced from a static context
    abtf.setText("" + fmt.format(Account.getBalance()));

这是我的帐户小程序类

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
import java.text.NumberFormat;


public class AccountApplet2 extends JApplet implements ActionListener
{    

  //  For West
  public JLabel  ai       = new JLabel("Account ID ");
  public JTextField  aitf = new JTextField();
  public JLabel  ab       = new JLabel("Account Balance ");
  public JTextField  abtf = new JTextField();

  //  For East
  public JButton     dp   = new JButton ("Deposit");
  public JTextField  dptf = new JTextField();
  public JButton       wt = new JButton ("Withdraw");
  public JTextField  wttf = new JTextField();

  // For South
  public JLabel  status   = new JLabel("");

  Account account = new Account(1234,1000);  // ******** here *******  

  public void init()
  {
    this.setSize(400, 90);

    //----------------------
    //  Set up the Structure
    //----------------------

    Container      c = getContentPane();
    JPanel         b = new JPanel(new BorderLayout());
    JPanel      west = new JPanel(new GridLayout(2,2));
    JPanel      east = new JPanel(new BorderLayout());
    JPanel depo_with = new JPanel(new GridLayout(2,2));

    // Add BorderLayout to the container
    c.add(b);

    // Add everything to West
    b.add(west, BorderLayout.WEST);
    west.setBorder(new TitledBorder("Display Account Information"));
    west.add(ai);
    west.add(aitf);
    aitf.setEditable(false);
    west.add(ab);
    west.add(abtf);
    abtf.setEditable(false);

    // Add everything to EAST
    b.add(east, BorderLayout.EAST); 
    east.setBorder(new TitledBorder("Deposit or Withdrawl Funds"));    
    east.add(depo_with, BorderLayout.EAST);    
    depo_with.add(dptf);
    depo_with.add(dp);
    depo_with.add(wttf);
    depo_with.add(wt);   
    dp.addActionListener(this);
    wt.addActionListener(this);

    // Add everything to SOUTH
    b.add(status, BorderLayout.SOUTH);



    refreshFields();

  }  // End intit

//-------------------------------------------------------------------------------------------------------------------------------------------------------
  public void actionPerformed(ActionEvent e)
  {


    if (e.getSource() == dp)  //  Executes if deposit was clicked
    {
      try 
      {   
        getAmount(dptf);
        account.deposit(Double.parseDouble(dptf.getText()));
        account.setBalance(Double.parseDouble(dptf.getText())); // doesnt update the balance 
        status.setText("Deposit processed");

        refreshFields();
      } 


      catch (NegativeAmountException nae) 
      {  
       status.setText(nae.getMessage() + " not allowed for deposit");
      }
      catch (EmptyFieldException efe) 
      {  
       status.setText(efe.getMessage() + " not allowed for deposit");
      }
      catch (Exception ex) 
      { 
       status.setText(ex.getMessage() + " not allowed for deposit");
      }    

    }    


    if (e.getSource() == wt)  //  Executes if withdraw was clicked
    {
      try 
      {
        getAmount(wttf);
        status.setText("Withdraw processed");

        refreshFields();
      } 
     // catch (InsufficientFundsException ife) 
     // {  
     //  status.setText(ife.getMessage() + " Insufficient funds");
     // }
      catch (NegativeAmountException nae) 
      {  
       status.setText(nae.getMessage() + " not allowed for withdraw");
      }
      catch (EmptyFieldException efe) 
      {  
       status.setText(efe.getMessage() + " not allowed for withdraw");
      }
      catch (Exception ex) 
      {
        // Something went wrong - handle your error here
        status.setText(" for withdraw");
      }

      refreshFields();
    }
  }


  public void refreshFields()
  {
    NumberFormat fmt = NumberFormat.getCurrencyInstance();
    aitf.setText("" + Account.getId());
    abtf.setText("" + fmt.format(Account.getBalance()));

    // diplays accound id and balance in left text fields
    //should be called when the applet is first displayed and after each valid transaction
  }

 public double getAmount(JTextField tf) throws EmptyFieldException,
                                               NumberFormatException,
                                               NegativeAmountException
 {
   double depo;

   try 
   {
     depo = Double.parseDouble(dptf.getText());  // read in one textfield and convert to a number
   } 
     catch (NumberFormatException nfe)  // catch NumberFormatException
   {
     throw nfe;  // catch throws NumberFormatException
   }



    return depo;
  }  //  End    



} // End Class

方法等所在的账户类

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;



public class Account
{
  int id         = 1234;
  double balance = 1000.00;

  Account (int id, double balance)
  {
    id      = 1234;
    this.balance = balance;
  }

  public int getId()
  {

    return id; 
  }

  public double getBalance()
  {
    return balance;   
  }

  public void setBalance(double balance) throws NegativeAmountException
  {
    if ( balance < 0)
      throw new NegativeAmountException();
    this.balance = balance;
  }

  public void deposit(double amount) throws NegativeAmountException
  {
    if (amount < 0)
    throw new NegativeAmountException();
    balance += amount;
  }

  public void withdraw(double amount) throws NegativeAmountException,
                                             InsufficientFundsException
  {

    if (amount <= balance )
    {
      throw new NegativeAmountException();
    }

    if (amount <= balance )
    {
      throw new InsufficientFundsException();
    }

    balance -= amount;


  }




}

【问题讨论】:

    标签: java try-catch call


    【解决方案1】:

    您正在整个程序中创建新的 Account 对象,并发现更改一个 Account 对象不会影响其他的 Account 对象。解决这个问题的关键是在 GUI 中创建 一个 Account 对象,单独对其进行更改,并在 GUI 中显示这些更改。要了解我的意思,请在您的代码中搜索new Account。您的程序中应该只有其中之一,并且不应在任何动作侦听器代码中。

    事实上,我会在程序的变量声明部分创建我的 Account 对象并完成它:

    public class AccountApplet2 extends JApplet implements ActionListener {    
        //  For West
        public JLabel  ai       = new JLabel("Account ID ");
        public JTextField  aitf = new JTextField();
        public JLabel  ab       = new JLabel("Account Balance ");
        public JTextField  abtf = new JTextField();
    
        //  For East
        public JButton     dp   = new JButton ("Deposit");
        public JTextField  dptf = new JTextField();
        public JButton       wt = new JButton ("Withdraw");
        public JTextField  wttf = new JTextField();
    
        // For South
        public JLabel  status   = new JLabel("");  
    
        Account account = new Account(1234,1000);  // ******** here *******
    

    另请注意,这是损坏的:

    Account (int id, double balance) {
        id = 1234;
        this.balance = balance;
    }    
    

    您完全忽略了传递给参数的 id。会更好

    Account (int id, double balance) {
        this.id = id;
        this.balance = balance;
    }    
    

    关于您的新“无法从静态上下文引用非静态方法”错误,请不要尝试在 Account 类上调用实例(非静态)方法。而是在帐户变量上调用它们(根据我上面的建议创建它之后)。

    例如,改变

    int id = Account.getId();
    

    int id = account.getId();
    

    但仅在您按照我上面的建议声明并初始化 Account 类型的帐户变量之后再说一次。

    请阅读Java and OOP Tutorial 了解更多关于类和变量(或实例)的关键概念>

    【讨论】:

    • 我删除了两个实例,只有 Account account=new Account(1234,1000); //其中 1234 是您的帐户 ID,1000 是您在类定义下方的初始余额,但这反过来又给了我错误 AccountApplet2.java:154: error: non-static method getId() cannot be referenced from a static context aitf .setText("" + Account.getId()); ^ AccountApplet2.java:155:错误:不能从静态上下文 abtf.setText("" + fmt.format(Account.getBalance())) 引用非静态方法 getBalance();在 refreshFields 方法中
    • @slow.learner:见编辑回答。至于您的下一个问题,请编辑您的问题并以格式化的方式显示代码,以便我阅读。但也要批判性地查看错误消息,因为它准确地告诉您出了什么问题——您在 Account 类而不是实例上调用 getBalance()
    • @slow.learner:getId() 相同。当您应该在该类的实例上调用它时,您在 Account class -- Acount.getId(); 上调用它。类和类的实例之间的这种区别是一个基本的 Java 核心概念,如果你想进步,最好理解这一点。请查看您有关此主题的书籍或教程并好好学习。
    • 如何在类的实例上调用它?我只被教过如何打电话给班级? - 我的课程没有文字,所以我必须在这个网站上学习
    • @slow.learner:什么?您已经在上述问题的代码中的类实例上调用它。注意 Account 类和 account 引用变量之间的区别——变量引用实例。您最好先阅读classes and OOP portion of the Java tutorial 的介绍(请参阅链接),因为这又是您绝对需要的关键知识。
    猜你喜欢
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多