MasterWali
MasterWali

Reputation: 31

How do I make this output a boolean?

So here's my code, I want the output to be like this:

Given two numbers, is the second input a multiple of the first?

For Example:

Input:

3

6

Output:

true

public boolean multiple(int m, int n){

    int i = 0;
    int j = 0;

    boolean check = true;
    if(n%m == 0){
        i++;
        return check;
    }
    else{
        j++;
        return false;
    }
}

When I try it I get an error, I think it's because the return statement is within the if and else statements.

Upvotes: 0

Views: 57

Answers (2)

Ankur Anand
Ankur Anand

Reputation: 3904

The code is perfectly fine .. Error must be Somewhere else

public class Test1 {
public static void main(String[] args) {
    System.out.println(multiple(3, 9));

}
    public static boolean multiple(int m, int n){

        int i = 0;
        int j = 0;

        boolean check = true;
        if(n%m == 0){
            i++;
            return check;
        }
        else{
            j++;
            return false;
        }
        }
}

Output true

here is output see IDEONE

Upvotes: 1

toadzky
toadzky

Reputation: 3846

The easiest way is to return the result of your if statement.

return n % m == 0;

I'm not sure what i/j are doing. You don't use them except to increment, but they are local to the function and get GC'd after the return. What you have now is basically this:

boolean bool = some_calculation();
if (bool == true)
{
    return true;
}
else
{
    return false;
}

Upvotes: 0

Related Questions