Return boolean from method that calls an Int

14,041

Your original question didn't actually specify programming language, and it's not clear why you think you need to "call an int".

However in most C-descendent languages, and keeping with the style of your code quote, the following should work

private static boolean result(int userIn)
{
    return (userIn % 2) == 0;
}

The expression (userIn % 2) == 0 will evaluate to a boolean (or your language's representation of one).

It is a common anti-idiom for people learning to program to do something like:

if (some condition is true)
then
    return TRUE
else
    return FALSE

Most (modern) programming languages allow you to simply return the result of evaluating a boolean condition, or to assign it to a suitably typed variable.

Thus

boolean result = (myvariable >= 10)

has the same result as, but is much more readable than:

boolean result
if (myvariable >= 10)
    result = TRUE
else
    result = FALSE

This may be what the person who set the assignment is wanting you to learn from it.

Share:
14,041
frillybob
Author by

frillybob

Updated on June 04, 2022

Comments

  • frillybob
    frillybob over 1 year

    As per instructions: Write a static method that takes one integer as a formal parameter and returns a Boolean value of True if the parameter value is even and False if the it odd. It would seem my method must call an int instead of a boolean. With that being said I don't know how to return a boolean from a method that calls an int. I've tried this but it doesn't work.

    EDIT - Language is JAVA. \nEDIT 2 - For anyone looking at this in the future, I originally meant to type private static int result. Not private static boolean result. That mistake ended up fixing my code.

    }
        private static boolean result(int userIn)
        {
            if (userIn % 2 == 0)
            {
                int yes = 1;
                return true;
            }
            else
            {
                return false;
            }
    
        }