[英]implementing a method that returns true if all argument is in the range
i want to implement method s
such as : 我想实现方法s
如:
given 2 int values, returns true if either of them is in the range 10..20 inclusive. 给定2个int值,如果其中一个值在10..20(含)范围内,则返回true。
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? 但是如何在不重复使用模式(x > 9 && x < 21)
且没有新方法的情况下实现呢? has a recursive solution? 有一个递归的解决方案?
Try this code using varargs and pass any number of int values to test. 使用varargs尝试此代码,并传递任意数量的int值进行测试。
implementing a method that returns true if any argument is in the range 实现一个方法,如果任何参数在范围内,则返回true
As per your question - returns true if either of them is in the range 10..20 inclusive. 根据您的问题-如果其中一个在10..20(含)范围内,则返回true。
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 如果所有参数都在范围内,则实现返回true的方法
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. 老实说,这只是一行代码的一半,实际上并没有重复。
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);
}
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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.