Array element is "9" when printed but not equals 9 in a comparison (==)

84 Views Asked by At

the code tells if the sum of every other element in an array of int (input 2) is equal to target (input 3).

public static boolean groupNoAdj(int start, int[] nums, int target) {
  if (nums.length<=2){
    System.out.println(nums[0]+""+target);
    return (nums[0]==target);
  }
  int hey = nums[start];
  int[] bleb = Arrays.copyOfRange(nums, start+2, nums.length);
  bleb[0] += hey;
  groupNoAdj(0, bleb, target);
  return false; // doesn't ever run
}

However, this only seems to work with an array with 1 element.

  • groupNoAdj(0, {9}, 9) returns true, as intended.
  • groupNoAdj(0, {3, 3294582, 6}, 9) returns false.

I added a print to print the values of both variables on line 3 System.out.println(nums[0]+""+target); which prints 99 (9 = num[0], 9 = target). nums[0]==target, then, should be true.

But groupNoAdj(0, {3, 3294582, 6}, 9) returns false, despite being 9. When either of the prompts of nums[0]==target is replaced with 9, false is also returned, despite the print code showing that both are 9.

1

There are 1 best solutions below

0
WJS On BEST ANSWER

The problem is that you are not returning from the recursive call at the end of the method. Replace

groupNoAdj(0, bleb, target);
return false; // doesn't ever run

with

 return groupNoAdj(0, bleb, target);