如何在Java中覆盖toString()方法?

时间:2018-02-17 05:13:40

标签: java override tostring

好的,所以在我正在处理的工作中,我有一个文件说明了注释,下面是我写的代码。我认为除了覆盖ToString方法之外我对一切都很好。我想我开始行好,我只是想弄清楚如何让输出结束。

这些是说明:

// Instruction 4
//TODO: Override the toString() method to return the account number,
//      account name, and account balance. The returned string should look
//      like:
//      Account: 10001 - General Expenses
//      Balance: 450.67

这是我到目前为止所做的:

public String toString(){
  return "Accounts: " + accountNumber + " " + accountName + " " + accountBalance;

以下是名为Account.java的整个文件:

// TODO: Add your name as a comment at the top of the code.
// Gary Hicks - CIT2551

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package finalexam;

import java.math.BigDecimal;

/**
 *
 * @author duvalls
 */
public class Account {
    private String accountNumber, accountName;
    private BigDecimal accountBalance;

    public Account(){
        accountNumber = "";
        accountName = "";
        accountBalance = new BigDecimal("0");
    }

    // Instruction 2 - create an overloaded constructor
    // TODO: Create an overloaded constructor that accepts parameters for 
    //       AccountNumber, AccountName, and AccountBalance. Assign the parameter
    //       values to the corresponding private variables.
    public Account(String accountNumber, String accountName, BigDecimal accountBalance)
    {
      this.accountNumber = accountNumber;
      this.accountName = accountName;
      this.accountBalance = accountBalance;
    }


    // Instruction 3 - create get and set methods for the properties.
    //************************************************************************   
    // TODO: Create getAccountNumber method to return the value of the private
    //       accountNumber variable.
    public String getAccountNumber(){
      return accountNumber;
    }

    //TODO: Create a setAccountNumber method that does not return a value and 
    //      accepts a String parameter. Assign the parameter's value to the 
    //      private accountNumber variable. 
    public void setAccountNumber ( String n ){
      accountNumber = n;
    }

    //************************************************************************    
    // TODO: Create getAccountName method to return the value of the private
    //       accountName variable.
    public String getAccountName(){
      return accountName;
    }

    //TODO: Create a setAccountName method that does not return a value and 
    //      accepts a String parameter. Assign the parameter's value to the 
    //      private accountName variable.    
    public void setAccountName ( String n ){
      accountName = n;
    }

    //************************************************************************

    // TODO: Create getAccountBalance method to return the value of the private
    //       accountBalance variable.
    public BigDecimal getAccountBalance(){
      return accountBalance;
    }    

    //TODO: Create a setAccountBalance method that does not return a value and 
    //      accepts a BigDecimal parameter. Assign the parameter's value to the 
    //      private accountBalance variable. 
    public void setAccountBalance ( BigDecimal n ){
      accountBalance = n;
    }

    // Instruction 4
    //TODO: Override the toString() method to return the account number,
    //      account name, and account balance. The returned string should look
    //      like:
    //      Account: 10001 - General Expenses
    //      Balance: 450.67
    public String toString(){
      return "Accounts: " + accountNumber + " " + accountName + " " + accountBalance;

    } 
}

这是另一个名为AccountJFrame.java的文件:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package finalexam;

import java.math.BigDecimal;
import javax.swing.JOptionPane;
import java.util.ArrayList;
/**
 *
 * @author duvalls
 */
public class AccountJFrame extends javax.swing.JFrame {
    ArrayList <Account> myAccounts = new ArrayList();
    /**
     * Creates new form AccountJFrame
     */
    public AccountJFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        createAccountButton = new javax.swing.JButton();
        listAccountsButton = new javax.swing.JButton();
        exitButton = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        accountNumberTextField = new javax.swing.JTextField();
        accountNameTextField = new javax.swing.JTextField();
        accountBalanceTextField = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Final Exam");

        jLabel1.setText("Account No:");

        jLabel2.setText("Account name:");

        jLabel3.setText("Account balance:");

        createAccountButton.setText("Create Account");
        createAccountButton.addMouseListener(new java.awt.event.MouseAdapter()
        {
            public void mouseClicked(java.awt.event.MouseEvent evt)
            {
                createAccountButtonMouseClicked(evt);
            }
        });

        listAccountsButton.setText("List Accounts");
        listAccountsButton.addMouseListener(new java.awt.event.MouseAdapter()
        {
            public void mouseClicked(java.awt.event.MouseEvent evt)
            {
                listAccountsButtonMouseClicked(evt);
            }
        });

        exitButton.setText("Exit");
        exitButton.addMouseListener(new java.awt.event.MouseAdapter()
        {
            public void mouseClicked(java.awt.event.MouseEvent evt)
            {
                exitButtonMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(accountNumberTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE)
                    .addComponent(accountBalanceTextField)
                    .addComponent(accountNameTextField, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(14, Short.MAX_VALUE)
                .addComponent(accountNumberTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(accountNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(accountBalanceTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(30, 30, 30))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(createAccountButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(exitButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(listAccountsButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(createAccountButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(listAccountsButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(exitButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void createAccountButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_createAccountButtonMouseClicked

        // Instruction 5
        // TODO: Create a BigDecimal variable named balance and
        //       assign the account balance entered in the TextField to it.


        //Instruction 6
        //TODO: Create an instance of the Account class named myAccount by calling the overloaded
        //      constructor and passing the entry made in the Account Number
        //      and Account Name TextFields and the balance BigDecimal variable.

        //Instruction 7
        //TODO: Use JOptionPane to show a message that contains the results 
        //      of calling the myAccount.toString() method.

        // Instruction 8
        //TODO: Add myAccount to the myAccounts ArrayList

        // Instruction 9
        //TODO: Clear the TextField controls

    }//GEN-LAST:event_createAccountButtonMouseClicked

    private void listAccountsButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listAccountsButtonMouseClicked

        String allAccounts = "";

        //Instruction 10
        //TODO: Loop through the myAccounts ArrayList. Inside of the loop, add  the result returned 
        //      from calling the toString() method for each Account object in the ArrayList
        //      to the allAccounts String variable. 

             JOptionPane.showMessageDialog(this, allAccounts, "Account List",
             JOptionPane.INFORMATION_MESSAGE);
    }//GEN-LAST:event_listAccountsButtonMouseClicked

    private void exitButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exitButtonMouseClicked
        // TODO: Add code to close the application
        System.exit(0);
    }//GEN-LAST:event_exitButtonMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AccountJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AccountJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AccountJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AccountJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AccountJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField accountBalanceTextField;
    private javax.swing.JTextField accountNameTextField;
    private javax.swing.JTextField accountNumberTextField;
    private javax.swing.JButton createAccountButton;
    private javax.swing.JButton exitButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton listAccountsButton;
    // End of variables declaration//GEN-END:variables
}

1 个答案:

答案 0 :(得分:2)

在长评论线程之后进行编辑找出问题:你需要创建一个新的Account实例,设置值,然后以某种方式调用它上面的toString,输出到你可以看到的地方。如新添加的说明6和7中所述。

这不是你的实际问题,但你应该在你所覆盖的方法上使用@Override注释。也就是说,你的IDE应该告诉你这个。

@Override
public String toString(){
  return "Accounts: " + accountNumber + " " + accountName + " " + accountBalance;

我将继续编辑实际的字符串,以便它符合你的作业。