2011-04-04 217 views
0
//******************************************************* 
// Account.java 
// 
// A bank account class with methods to deposit to, withdraw from, 
// change the name on, charge a fee to, and print a summary of the account. 
//******************************************************* 
import java.text.NumberFormat; 

public class Account 
{ 
    private double balance; 
    private String name; 
    private long acctNum; 

    //---------------------------------------------- 
    //Constructor -- initializes balance, owner, and account number 
    //---------------------------------------------- 
    public Account(double initBal, String owner, long number) 
    { 
    balance = initBal; 
    name = owner; 
    acctNum = number; 
    } 

    //---------------------------------------------- 
    // Checks to see if balance is sufficient for withdrawal. 
    // If so, decrements balance by amount; if not, prints message. 
    //---------------------------------------------- 
    public void withdraw(double amount) 
    { 
    if (balance >= amount) 
     balance -= amount; 
    else 
     System.out.println("Insufficient funds"); 
    } 

    //---------------------------------------------- 
    // Adds deposit amount to balance. 
    //---------------------------------------------- 
    public void deposit(double amount) 
    { 
    balance += amount; 
    } 

    //---------------------------------------------- 
    // Returns balance. 
    //---------------------------------------------- 
    public double getBalance() 
    { 
    return balance; 
    } 


    //---------------------------------------------- 
    // Returns a string containing the name, account number, and balance. 
    //---------------------------------------------- 
    public String toString() 
    { 
    NumberFormat fmt = NumberFormat.getCurrencyInstance(); 

    return (acctNum + "\t" + name + "\t" + fmt.format(balance)); 
    } 

    //---------------------------------------------- 
    // Deducts $10 service fee 
    //---------------------------------------------- 
    public double chargeFee() 
    { 
    balance=balance-10; 
    return balance; 
    } 

    //---------------------------------------------- 
    // Changes the name on the account 
    //---------------------------------------------- 
    public void changeName(String newName) 

    { 
    name=String.toString(newName); 
    } 

} 

我需要該程序的最後部分的幫助//更改帳戶上的名稱。我需要將它作爲一個字符串(名稱)作爲參數,並將其更改爲新字符串(newName),那麼正確的語法是什麼?我無法在我的書中找到它。字符串作爲參數

+0

爲什麼要調用String.toString(newName),如果newName已經是一個字符串?它應該是name = newName; – Andre 2011-04-04 19:22:37

回答

1

這將會是:

public void changeName(String newName) 
{ 
    name=newName; 
} 
2
name = newName; 

會工作得很好。字符串是不可變的,所以不能在之後改變。