binibiningtinamoran

File_Letter_Counter

Oct 16th, 2019
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.18 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.io.*;
  3.  
  4. public class File_Letter_Counter {
  5.     public static void main(String[] args) {
  6.         char letter;
  7.         Scanner in = new Scanner(System.in);
  8.  
  9.         String inputFile;
  10.  
  11.         try {
  12.             System.out.print("Enter name of file to be read: ");
  13.             inputFile = in.nextLine();
  14.  
  15.             System.out.print("Enter letter to find: ");
  16.             letter = in.next().charAt(0);
  17.  
  18.             File file = new File(inputFile);
  19.             Scanner scanFile = new Scanner(file);
  20.  
  21.  
  22.             int totalCount = 0;
  23.             String line;
  24.             while (scanFile.hasNext()) {
  25.                 line = scanFile.nextLine();
  26.                 for (int i = 0; i < line.length(); i++) {
  27.                     if (line.charAt(i) == letter) {
  28.                         totalCount++;
  29.                     }
  30.                 }
  31.             }
  32.             System.out.printf("\n%c occurred %,d %s in %s.\n", letter, totalCount,
  33.                     totalCount > 1 ? "times" : "time", inputFile);
  34.             System.out.println();
  35.         } catch (FileNotFoundException ex) {
  36.             System.out.println(ex.getMessage());
  37.         }
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment