Find words next to substring

Assignment

Solution 

public static void findWordsBeside(final String searchWord, final String fileName) {

finalStringBuilder result = new StringBuilder();

Scanner in = null;

try {

in = new Scanner(new File(fileName));

while (in.hasNextLine()) {

final String line = in.nextLine();

if (line.indexOf(searchWord) >= 0) {

final String[] words = line.split(“\\s+”);

int previous = -1;

for (int i = 0; i <words.length; i++) {

if (words[i].equals(searchWord)) {

if (i > 0 && i – 1 != previous && !words[i – 1].equals(searchWord)) {

result.append(words[i – 1]).append(” “);

}

if (i + 1 <words.length&& !words[i + 1].equals(searchWord)) {

result.append(words[i + 1]).append(” “);

previous = i + 1;

}

}

}

}

}

if (result.length() > 0) {

result.delete(result.length() – 1, result.length());

}

System.out.println(result.toString());

} catch (final IOExceptionioe) {

System.out.println(“could not read file ” + fileName);

} finally {

if (in != null) {

in.close();

}

}

}