Sevajper Sevajper - 14 days ago 9
Java Question

Sorting an array through my method error Java

I am newer to programming and I need some help. I am supposed to make my own method checking if one array has a subsequence to another one. Meaning if the first array is {1, 2, 3, 4, 5} and the second one is {1, 2, 3} the second one is a subsequence of the first. However if the first is {1, 2, 3, 4, 5} and the second is {1, 4, 5} it is not a subsequence, so the second has to be in order as well.

I have tried to do it this way through strings:

private static boolean subs(int[] array, int[] subsequence) {
String a = Arrays.toString(array);
String b = Arrays.toString(subsequence);
boolean c = false;

if (a.equals(b)) {
return true;
}

for (int i = 0; i < a.length(); i++) {
if (!(b.equals(a.substring(i, b.length() + i)))) {
c = false;
} else {
c = true;
break;
}
}
if (c == true) {
return true;
} else {
return false;
}
}


However I get 3 errors, here is the printscreen :

enter image description here

And here is how I am testing the method:

int[] fArray = { 1, 2, 3, 4, 5 };
int[] tempArray = { 2, 3, 4 };
System.out.println(subs(fArray, tempArray));


I know I probably made a lot of mistakes, so hit me with it.

Answer

Here:

for (int i = 0; i < a.length(); i++) {
  if (!(b.equals(a.substring(i, b.length() + i)))) {

Your outer loop condition makes sure that i stays smaller than a.length(). But then you try to take a substring within a that goes for b.length()+i!

In other words: for any b.length() > 0 ... that code will always try to fetch characters beyond the end of a.

And there is also a bug in your result handling - it seems very much possible that you assign

c = true;

at some point; to later overwrite that with

c = false;

In other words: your code forgets that he found a match! The much easier solution: when hitting the true case, just return true there! And if you don't return within the loop; you just return false in the end.

Finally: although it seems like a cool idea to turn your arrays into strings ... that doesn't really buy you anything. You are still doing the work of going through the first array and checking if the second is in there. Writing code that does that directly on the provided arrays ... would not be much different from what you got there with your "string detour".

Edit: when using multiple returns in a method, you simply have to make sure that any possible path has a return statement. In your case:

boolean subs(... {

   if equal strings
     return true

   for i as index in a
      if a.substring equals b
        return true

   return false