java - This program asks the user for a file name and displays the occurrences of each character( for example: a=2, b=3.... z=5) in the text file -


i have program asks file name not sure next, how can make method count occurrences of each letter in text file(and need use tolower , toupper)

so please help.. thank you

here code:

import java.util.*; import java.io.*;  public class fileopener {      public static void main(string[] args) throws ioexception     {          scanner input = new scanner(system.in);         int[] array = new int[26];         string[] alphabets = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",                  "t", "u", "v", "w", "x", "y", "z"};          //string lines = input.nextline().touppercase();         //string path = input.nextline();         // prompt user file name         system.out.print("enter file name: ");         string filename = input.nextline();         //char lines = input.next().touppercase().charat(0);         // open file         file file = new file(filename);          // ensure file exist         if(!file.exists()){             system.out.println("the file " + filename + " not exist.");             system.exit(0);         }          // create scanner file         scanner inputfile = new scanner(file);          string line = null;         int count = 0;         while(inputfile.hasnextline()){             line = inputfile.nextline();             count += line.length();         }              //system.out.println(inputfile)         system.out.println("the file size " + count + " characters");             // close file         inputfile.close();          for(char c : line.tochararray()){             array[97 - 'a']++;         }         for(char c = 'a'; c <= 'z'; c++){             if(array[c - 'a'] != 0){                 system.out.println(c + " => " + array[97 - 'a']);             }         }      } } 

a simple, possibly not efficient way of counting number of occurrences of each letter create integer array of same size alphabets string array. , increment every time index matches.

        string alphabets = "abcdefghijklmnopqrstuvwxyz";          string filename = "somefilename";         int[] charcount = new int[alphabets.length()];         string[] namearray = filename.split("");          for(int = 0; < namearray.length; i++) {             charcount[alphabets.indexof(namearray[i])]++;         }          for(int = 0; < namearray.length; i++) {             system.out.println(charcount[i]);         } 

there exist more sophisticated solutions, should give integer array of counts of corresponding alphabets in alphabets string array.


Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -