I was trying out the JetBrains course of Java Core. This is the exercise:
Let's implement the simplest search engine possible ever. It should search for a specific word in a multi-word input line. The input line contains several words separated by a space. The words are numbered according to their order, with the first word having index 1. Consider that all the words in the line are unique, so there can be no repetition. Write a simple program that reads two lines: a line of words and a line containing the search word. The program must search in the first line for a word specified in the second one. The program should output the index of the specified word. If there is no such word in the first line, the program should print Not Found. Please remember that indexes start from 1! You should output exactly one line. The lines that start with > represent the user input. Note that these symbols are not part of the input.
Example 1:
"> first second third fourth" "> third" "3"
Example 2:
"> cat dog and mouse" "> elephant" "Not found"
This is my code:
package search;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String sc1 = scanner.nextLine();
String[] splited = sc1.split("\\s+");
String sc2 = scanner.nextLine();
int index = 0;
boolean flag = false;
for (int i = 0; i <= splited.length - 1; i++) {
if (sc2.contains(splited[i])) {
flag = true;
index = i+1; //line updated, same result
}
}
if (flag) {
System.out.println(index);
}
else {
System.out.println("not found ");
}
}
}
And this is the answer:
Wrong answer in test #1
Please find below the output of your program during this failed test. Note that the '>' character indicates the beginning of the input line.
"---"
"> hello my name is alex"
"> my"
"1"
Update: Thanks a lot for your comments @shriakhilc and @Gardener. I updated the code, as per Gardener's advice, and now it gives me this example:
what a beautiful place what 2
What could I do to make it count from 1? (I also tried changing the initial values of both i and index separately and doesn't work either, also modified length but nothing either.)