incompatible type: cannot convert void to an int

10k views Asked by At

I created this method in my BankAccount class and would like to call it in a different class called Demo. But when I try and call the second class I get an error saying:

incompatible types: void cannot be converted to an int.

public void makeDeposit(int amount) { 
    if ( account != AccountType.LOAN ) {
        if ( balance >= 0) {
            balance = (balance + amount); 
        }
    }
} 

So how could I call this method into another class and convert it into an int?

The code that throws the above error is:

public class Demo {
    public static void SavingsAccount() {
        BankAccount acc = new BankAccount(0, 0.5);
        int hi = acc.makeDeposit(100);
     } 
}

By the way, I am using blueJ, if it matters.

2

There are 2 answers

3
0909EM On

Your method needs a return type - it should be

public int makeDeposit(int amount)

This is really part of the language and you should look it up rather than asking here...

3
Neil Locketz On

The way your calling the method requires it to return an int. You are probably assigning the return value to something. You need to change the method signature to say public int makeDeposit(int amount) and have it return an integer.

Alternatively you could change your code not to assign the return value of that method.