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. I believe the containsOpposites method does work but the main method only returns true, even if the array contains no opposite elements. 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];
you end up with an array that looks like [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
. You then overwrite the first 4 elements, but the remaining 6 are still 0
. Since -0 == 0
evaluates to true
, your code thinks there are opposites.
See this question about how Java initializes arrays depending on the data type.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.