Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

****JAVA****** Within a *word.txt* file there are many words listed in it, each

ID: 3700601 • Letter: #

Question

****JAVA****** Within a *word.txt* file there are many words listed in it, each word takes one line. In the program, write code to read in words from the given file, then prompt the user for two words and print out how many words in the file fall between those words. If one of the two words is not contained in the file, then output "word1 or word 2 is not found in the file."

Sample output:

type in the two words: good and night

or night is not found.

Sample output:

type in the two words: hello and computer

are 1234 words between hello and computer

Explanation / Answer

import java.util.ArrayList;
import java.io.File;
import java.util.Scanner;

public class HowMany{
public static void main(String[] args) {
  ArrayList<String> words = new ArrayList<>();
  String word1 = "";
  String word2 = "";
  try{
   Scanner fsc = new Scanner(new File("word.txt"));
   while(fsc.hasNextLine()){
    words.add(fsc.nextLine());
   }
   fsc.close();
  }catch(Exception e){
   System.out.println("Error occured in Reading File");
   System.exit(0);
  }
  System.out.print("Please Type in Two words : ");
  Scanner sc = new Scanner(System.in);
  word1 = sc.next();
  word2 = sc.next();
  int n1 = words.indexOf(word1);
  int n2 = words.indexOf(word2);
  if(n1 == -1 || n2 == -1){
   System.out.println(word1+" or "+word2+" is not found");
  }else{
   System.out.println("There are "+Math.abs(n2-n1-1)+" words between "+word1+" and "+word2);
  }
}
}