[英]How do I check for a boolean for existence of a number between a range of two numbers in java?
I cannot figure out how to prove an existence is true or not; 我无法弄清楚如何证明存在是正确的。
static boolean existsx(double p1x, double p2x,double[] varray) {
boolean foundx = false;
int i;
//System.out.println(varray.length);
for (double v : varray){
if ( varray[i] > p1x && v < p2x) {
foundx = true;
//System.out.println(x+" was found to be between"+p1x+" and "+p2x);
break;
}
else {
foundx = false;
}
}
return foundx;
}
I'm trying to check for an existence of a number in an array between p1x and p2x. 我正在尝试检查p1x和p2x之间的数组中是否存在数字。 If it is true then, return true, else return false. 如果为true,则返回true,否则返回false。
You're trying to use a mixture of the enhanced for
loop and a "normal" for
loop. 您正在尝试混合使用增强的for
循环和“普通”的for
循环。 Also, you're going through hoops to avoid multiple exits. 另外,您要避免各种退出。 I'd rewrite it as: 我将其重写为:
static boolean existsx(double p1x, double p2x, double[] varray) {
for (double v : varray){
if (v > p1x && v < p2x) {
return true;
}
}
return false;
}
(Note that that's currently *excluding p1x
and p2x
; you may want to make at least one bound inclusive, depending on your needs. Renaming the parameters and method wouldn't hurt, either.) (请注意,当前* p1x
和p2x
;根据您的需要,您可能希望至少包含一个边界。重命名参数和方法也不会受到损害。)
I think you have a few logical issues, declaring the variable i
without ever initializing it being one of them. 我认为您有一些逻辑问题,在没有初始化变量i
情况下声明变量i
就是其中之一。
The following code should tell you if one of the numbers in the given array is in between those two: 下面的代码应告诉您给定数组中的数字之一是否位于这两个之间:
static boolean existsx(double p1x, double p2x,double[] varray){
double upperBound = Math.max(p1x, p2x);
double lowerBound = Math.min(p1x, p2x);
for (double number : varray)
{
if ( (number <= upperBound) && (number >= lowerBound))
{
return true;
}
}
return false;
}
public static boolean exists(double p1, double p2, double[] varray)
{
for(double v : varray)
if(v >= p1 && v <= p2) return true;
return false;
}
You could also use a SortedSet (if you need to do the look up often and the varray is large it should be faster is you create it once): 您也可以使用SortedSet(如果需要经常查找并且varray很大,那么一旦创建一次,它应该会更快):
import java.util.SortedSet;
import java.util.TreeSet;
public class TestSortedSet {
public static void main(String[] args) {
double p1 = 2;
double p2 = 4;
double[] varray = { 3.0 };
TreeSet<Double> set = new TreeSet<Double>();
for(double d : varray) {
set.add(d);
}
SortedSet<Double> between = set.subSet(p1, p2);
System.out.printf("%s number(s) between %s and %s: %s", between.size(), p1, p2, between);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.