-1

enter image description here[enter image description here][2]I have tried getting rid of the local variable and making i increment but x.length() but that produces a yellow underline as well. Does anyone know what I'm missing?

public static boolean isCat(String s, String x) {
    int xlen = x.length();
    for (int i = 0; i < s.length(); i += xlen) {
        if (s.substring(0, i).equals(x)) {
            return true;
        }
        return false;
    }
}

problem

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • 1
    Hello and welcome to Stack Overflow! Please [edit] the question and include the code as text, not as image. – Turing85 Jan 01 '21 at 19:43
  • When you hover over the yellow line with your mouse cursor, what is the warning saying? – Progman Jan 01 '21 at 20:03
  • On first iteration `i=0`, so `substring(0, i)` returns an empty string. If `"".equals(x)` the method returns `true`. If not, the method returns `false`. The method never gets to the second iteration of the loop. As written, the method might as well be `return x.isEmpty();` – Andreas Jan 01 '21 at 21:05

1 Answers1

3

Because your loop will return true or false before the increment step. Thus the increment is "dead code". Move return false; after the loop body. Or,

public static boolean isCat(String s, String x) {
    return s.contains(x);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249