java - Reading a text file using Scanner and count every time each alphabet appear -
so have assignment array. asked use scanner read through text files , record occurrences of each alphabet , store them in table.
for example:
public class { char[] alphabet = "abcdefghijklmnopqrstuvwxyz".tochararray(); public void displaytable () { (int = 0; < alphabet.length; i++) { system.out.println(alphabet[i] + ": " + count); } }
i don't know how construct method store occurrences of each alphabet.
it supposed like:
public void countoccurrences (scanner file) { //code written here }
if text file has line , line :
hello world
the method ignore integers or symbols , output char appeared in table.
d: 1 e: 1 h: 1 l: 3 o: 2 r: 1 w: 1
i can't figure out myself , appreciated!
thanks, shy
simply use map
. read inline comments more info.
map<character, integer> treemap = new treemap<character, integer>(); // initialize default value 0 characters (char = 'a'; <= 'z'; i++) { treemap.put(i, 0); } char[] alphabet = "hello world".tochararray(); (int = 0; < alphabet.length; i++) { // make lower case char ch = character.tolowercase(alphabet[i]); // value , update 1 // check characters if (treemap.containskey(ch)) { treemap.put(ch, treemap.get(ch) + 1); } } // print count (char key : treemap.keyset()) { int count = treemap.get(key); if (count > 0) { system.out.println(key + ":" + treemap.get(key)); } }
output hello world ignore case
d:1 e:1 h:1 l:3 o:2 r:1 w:1
read file line line. iterate character of line , update occurrence in map.
Comments
Post a Comment