-9

im trying to get the index of a character using only the charAt and length methods for strings. this is what the question asks :Declare a public method called indexOf that takes a character parameter and returns the index in the stored string of the first occurrence of that character or -1 if the character is not found. this is what i did.

public int indexOf(char c){
    for(i=0; i <string.length - 1; i++){
    if(string.charAt(c) == string.charAt(i)){
    return i;
    else {
    return -1;
    }
    }

2 Answers2

3

You need a for loop from 0 to length()-1, and test the value equality of charAt(index) with the given character.

T.Gounelle
  • 5,953
  • 1
  • 22
  • 32
0
public static int indexOf(String word, char c) {
    int index = -1;
    for (int i = 0; i < word.length(); i++) {
        if (word.charAt(i) == c){
            index = i;
            break;
        }
    }
    return index;
}

Explanation provided by : @Abbé Résina.

Code Whisperer
  • 1,041
  • 8
  • 16