如何从驱动程序调用void方法

时间:2014-05-08 01:45:49

标签: java

好像我不能称之为退出方法..我做错了什么?

public class BankAccount {
    double balance;

    BankAccount(double openingBalance){
        balance=openingBalance;

    public double getBalance(){
        return balance; 
    }
    public void deposit(double amount){
        balance += amount;
    }
    public void withdraw (double amount){
        if (balance > amount){
            balance -= amount;  
        }else if (amount > balance){
            System.out.print("Error");
        }else if (amount == balance){
            balance = 0;
        }
    }
}

我的驱动程序类

public class Driver {

    static BankAccount acc1;

    public static void main (String[] args){

        BankAccount  acc1 = new BankAccount (1500);
        acc1.deposit(1500);
        acc1.withdraw(1000);

        System.out.println("Withdrawl Amount: $" +acc1.withdraw(I GET AN ERROR) +"Deposit: $" +acc1.balance);

1 个答案:

答案 0 :(得分:0)

问题是你正在调用acc1.withdraw(...)并试图将它返回的任何内容附加到String。由于withdraw方法返回void,这是无效的语法。它不清楚你真正想要的是什么,但是如果你想因为某种原因将withdraw的返回值附加到String,那么撤回需要返回一些东西。也许你想要这样的东西......

public class BankAccount { 
    double balance;

    BankAccount(double openingBalance){
        balance=openingBalance;
    }

    public double getBalance(){
        return balance;
    }
    public void deposit(double amount){
        balance += amount;
    }
    public double withdraw (double amount){
        if (balance > amount){
            balance -= amount;
        }else if (amount > balance){
            System.out.print("Error");
        }else if (amount == balance){
            balance = 0;
        }
        // you can return the amount, or the balance, or whatever you want here...
        return amount;
    }
}

调用方法的一种方法......

public class Driver {

    public static void main (String[] args){
        BankAccount  acc1 = new BankAccount (1500);

        System.out.println("After Withdrawing Amount: $" +acc1.withdraw(50) +" The New Balance: $" +acc1.balance);
    }
}
相关问题