[英]How to get correct Test Method Syntax
I think I am doing something very inefficient here, but I am trying to make a test method that checks if my containsOpposites method works. 我认为我在这里做的事情效率很低,但是我试图做一个测试方法来检查我的containsOpposites方法是否有效。 I believe the containsOpposites method does work but the main method only returns true, even if the array contains no opposite elements.
我相信containsOpposites方法确实可以工作,但是main方法仅返回true,即使该数组不包含相反的元素也是如此。 What am I doing wrong?
我究竟做错了什么?
boolean containsOpposites(int[] a) {
for (int i=0;i<a.length; i++){
for (int k= i+1; k<a.length; k++){
if (a[i]== -a[k]){ return true;
}
}
}
return false;
}
String test (int []a) {
if (containsOpposites(a)) {return "true";}
else return "false";
}
public void main (String[] args) {
int []l = new int[10]; /*this array contains no negative elements but the test
method return true*/
l[0]=1;
l[1]=2;
l[2]=3;
l[3]=2;
System.out.println("" + test(l));
}
When you do this int []l = new int[10];
执行此操作时,
int []l = new int[10];
you end up with an array that looks like [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
. 您最终得到一个看起来像
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
的数组。 You then overwrite the first 4 elements, but the remaining 6 are still 0
. 然后,您覆盖前4个元素,但其余6个仍为
0
。 Since -0 == 0
evaluates to true
, your code thinks there are opposites. 由于
-0 == 0
计算结果为true
,因此您的代码认为相反。
See this question about how Java initializes arrays depending on the data type. 请参见有关Java如何根据数据类型初始化数组的问题 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.