Reputation: 39
I am writing a program with many methods for an assignment, and in one of the methods, I need to find the index where character c starts in string s. for example:
IN: sheep, h
OUT: 1
I have done this method but with two strings instead of a string and a character
public static int findInStr1(String s1, String s2) {
for (int i = 0; i < s1.length() - s2.length(); i++) {
boolean found = true;
for (int j = 0; j < s2.length(); j++) {
if (s1.charAt(i) != s2.charAt(j)) {
found = false;
break;
}
}
if (found) {
return i;
}
}
return -1;
}
I tried to move some things around to make it work with a char instead of a second string
public static int findInStr2(String s1, char c) {
for (int i = 0; i < s1.length() - 1; i++) {
boolean found = true;
if (s1.charAt(i) != c) {
found = false;
break;
}
if (found) {
return i;
}
}
return -1;
}
but it always returns -1 no matter the input
Thanks in advance
Upvotes: 0
Views: 112
Reputation: 3306
When its not found the first time around you set found to false and break
, NOTE:break
breaks out of the whole Loop not the if statement and hence -1 is returned
Try to write more compact and simpler code , The code below does exactly what you want ,
import java.util.*;
public class Found{
public static int findInStr2(String s1, char c) {
for (int i = 0; i < s1.length(); i++)
{
if (s1.charAt(i)==c)
{
return i;
}
}
return -1;
}
public static void main(String[] args)
{
Found f=new Found();
int pos=Found.findInStr2("Hello",'o');
System.out.println("found at position"+(pos+1));
}//main ends
}//class ends
Upvotes: 1
Reputation: 750
Try this
for (int i = 0; i < s1.length() - 1; i++) {
if (s1.charAt(i) == c) {
return i;
}
}
return -1;
Upvotes: 1
Reputation: 1767
I don't think you need the break statement. This is breaking you out of the for loop early.
You should be able to prove this by adding a system.out.println before the boolean found declaration to trace what your index is.
Upvotes: 1
Reputation: 82579
this line:
if (s1.charAt(i) != c) {
What does it do? It looks to see if the character is NOT the goal you're looking for. So in most cases, this triggers on the first character.
Next, you have a break statement BEFORE you have your return statement. Remember, break is just for loops, not for if statements. If you find it, don't use a found variable. Just return the index right then and there.
if (s1.charAt(i) == c) {
return i;
}
Lastly, you have this as your for condition:
for (int i = 0; i < s1.length() - 1; i++)
You have to pick one or the other. Either use <= s1.length() - 1
or use < s1.length()
. If you do both, you'll miss the last character. So "sheep", 'p'
returns not found when it should return 4.
Upvotes: 3