문제

i want to implement method s such as :

given 2 int values, returns true if either of them is in the range 10..20 inclusive.

simple answer is:

public boolean s(int a, int b) {    
    return (a > 9 && a < 21) ||  (b > 9 && b < 21);
}

but how implement without duplicated use of pattern (x > 9 && x < 21) and without new method? has a recursive solution?

도움이 되었습니까?

해결책 2

If you're looking for a recursive solution, then I would suggest this:

public static boolean s(int a, int b) {
    if (b == 0) {
        return (a > 9 && a < 21);
    }
    return (a > 9 && a < 21) || s(b, 0);
}

However, this is far less readable than your original solution.


EDIT Per @طاهر, a more concise version

public static boolean s(int a, int b) {
    boolean r = (a > 9 && a < 21); 
    return b == 0 ? r : r || s(b, 0); 
}

다른 팁

Try this code using varargs and pass any number of int values to test.

implementing a method that returns true if any argument is in the range

As per your question - returns true if either of them is in the range 10..20 inclusive.

public boolean s(int... a) {
    for (int i : a) {
        if (i > 9 && i < 21) {
            return true;
        }
    }
    return false;
}

--EDIT--

implementing a method that returns true if all argument is in the range

public static boolean s(int... a) {
    for (int i : a) {
        if (i < 10 || i > 20) {
            return false;
        }
    }
    return (a.length > 0);
}

--EDIT--

put a check if needed in the beginning of the method but I never suggest you to use it.

    if (a.length != 2) {
        throw new IllegalArgumentException("It accepts only two arguments");
    }

--EDIT--

as per your requirement if you can't change the method signature that may come from an interface or super class.

public boolean s(int a, int b) {

    int[] array = new int[] { a, b };

    for (int i : array) {
        if (i > 9 && i < 21) {
            return true;
        }
    }
    return false;
}

Either add a new method, or let this "code duplication" live. It's one (half) of line of code, it's not really duplicated, to be honest.

You can also try this but it's not the best solution :

public static boolean s(int a, int b) {
    int n = a * b;
    if (a == 0)
        n = b;
    if(b == 0)
        n = a;
    for (int i = 10; i < 21; i++)
        if( n % i == 0 )
            return true;
    return false;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top