In the first program, you are provided a word.txt file. Within the file there ar
ID: 3698860 • Letter: I
Question
In the first program, you are provided a word.txt file. Within the file there are many words listed in it, each word takes one line. In you program. Write Java 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 tell word1 or word 2 is not found in the file.
output:
Please type in the two words: good and night
good or night is not found.
output:
Please type in the two words: hello and computer
There are 1234 words between hello and computer
Hint: you can use binarySearch method to figure out the index for the two words
The word.txt file isn't provided here but i am having a tough time implementing code to perform the required action. Any help is greatly appreciated!
Explanation / Answer
here is your program : ---------------->>>>>>>>>>>>
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);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.