In: Computer Science
Thanks for the question. Below is the code you will be needing. Let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please leave a +ve feedback : ) Let me know for any help with any other questions. Thank You! =========================================================================== import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class WordsInBetween { public static void main(String[] args) { String fileName = "words.txt"; int firstWordPosition = -1; int secondWordPosition = -1; try { Scanner fileReader = new Scanner(new File(fileName)); Scanner keyboard = new Scanner(System.in); System.out.print("Please type in two words: "); String firstWord = keyboard.next(); String secondtWord = keyboard.next(); String wordRead; int wordCount = 0; while (fileReader.hasNext()) { wordRead = fileReader.next().toLowerCase(); wordCount += 1; if (wordRead.contains(firstWord.toLowerCase())) { firstWordPosition = wordCount; } else if (wordRead.contains(secondtWord.toLowerCase())) { secondWordPosition = wordCount; if (firstWordPosition != -1) { break; } } } fileReader.close(); if (firstWordPosition == -1 && secondWordPosition == -1) { System.out.println("Both words are not found!"); } else if (firstWordPosition == -1) { System.out.println(firstWord + " is not found."); } else if (secondWordPosition == -1) { System.out.println(secondtWord + " is not found."); } else { System.out.println("There are " + (secondWordPosition - firstWordPosition - 1) + " words between " + firstWord + " and " + secondtWord); } } catch (FileNotFoundException e) { System.out.println("Error: Could not open/read file: " + fileName); return; } } }
===========================================================================