Write a program that reads a book using next(); (you will need to use a file loo
ID: 3621641 • Letter: W
Question
Write a program that reads a book using next(); (you will need to use a file loop)
and counts how many occurances match a particular word.
(you will need to use the equalsIgnoreCase string method.)
Ask the user what word to count before the loop starts.
here is a sample run:
What word do you want to count?
the
34253 matches to the were found
Explanation / Answer
import java.util.*; import java.io.*; public class Counter { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); String fileName; String word; File file; Scanner reader; int count = 0; System.out.print("Enter a file name to read: "); fileName = keyboard.next(); System.out.print("Enter a word you wish to count: "); word = keyboard.next(); if (fileName.length() > 3) { file = new File(fileName); try { reader = new Scanner(file); while (reader.hasNext()) { if (reader.next().equalsIgnoreCase(word)) count++; } System.out.println(count + " matches to " + word + " were found."); } catch (Exception e) { System.out.println(e.getStackTrace()); } } } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.