I need to write method that will chek “String str” on other string, and return the index that the str starts.
That’s sound like homework, and it is some of homework but for my use to learn for a test…
i’ve tried:
public int IndexOf (String str) {
for (i= 0;i<_st.length();i++)
{
if (_st.charAt(i) == str.charAt(i)) {
i++;
if (_st.charAt(i) == str.charAt(i)) {
return i;
}
}
}
return -1;
}
but i dont get the right return. why? i’m on the right way or don’t even close?
I am afraid, you are not close.
Here’s what you have to do:
indexOf, I will call this the master) (you are going this right)Something like:
Some other points:
lower case letter by convention
(meaning, the compiler won’t
complain, but your fellow programmers
may). So
IndexOfshould actually beindexOf(class level variables) start with a
_(as in_st) is not a really goodpractice. If your professor insists,
you may not have many options, but
keep this in mind)