Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.io.*;
- public class File_Letter_Counter {
- public static void main(String[] args) {
- char letter;
- Scanner in = new Scanner(System.in);
- String inputFile;
- try {
- System.out.print("Enter name of file to be read: ");
- inputFile = in.nextLine();
- System.out.print("Enter letter to find: ");
- letter = in.next().charAt(0);
- File file = new File(inputFile);
- Scanner scanFile = new Scanner(file);
- int totalCount = 0;
- String line;
- while (scanFile.hasNext()) {
- line = scanFile.nextLine();
- for (int i = 0; i < line.length(); i++) {
- if (line.charAt(i) == letter) {
- totalCount++;
- }
- }
- }
- System.out.printf("\n%c occurred %,d %s in %s.\n", letter, totalCount,
- totalCount > 1 ? "times" : "time", inputFile);
- System.out.println();
- } catch (FileNotFoundException ex) {
- System.out.println(ex.getMessage());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment