cody53982
cody53982

Reputation: 21

What is wrong with my code for this Edabit challenge?

  public static String findNemo(String sentence) {
    int nemoIndex = sentence.indexOf("Nemo");
    if(nemoIndex!=-1){
    return "I found Nemo at "+nemoIndex+1+"!";
    }
    else{
      return "I can't find Nemo :(";
    }
  }
}

This problem deals with arrays, formatting, and strings but I'm not sure what I'm doing wrong here. Challenge Description Below: enter image description here

Upvotes: 0

Views: 439

Answers (2)

Barak David
Barak David

Reputation: 45

// The following is a solution to the challenge question. It works by first splitting the string into an array of separate words. The function then loops through the array to find the index position (result) at keyword "Nemo". If the keyword does not exist, it returns "I can't find Nemo :(, and if "Nemo" exists, it will return "I found Nemo at -index position-//

function findNemo(string) {
  let array = string.split(" ");
  let result = array.findIndex((element) => element === "Nemo") + 1;
  if (result === 0) {
    return "I can't find Nemo :(";
  }
  return "I found Nemo at " + result + "!";
}
exports.solution = findNemo;

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201497

Your current code finds the index of the character at which "Nemo" begins, not the count of words before "Nemo". Split your input by white space, and then iterate the tokens from the split; if you find a match return the index. Like,

public static String findNemo(String sentence) {
    String[] tokens = sentence.split("\\s+");
    for (int i = 0; i < tokens.length; i++) {
        if (tokens[i].equals("Nemo")) {
            return String.format("I found Nemo at %d!", i + 1);
        }
    }
    return "I can't find Nemo :(";
}

Upvotes: 1

Related Questions