Question: I want to rewrite the code below so it can t aking input from a file called String.txt import java.util .*; public class CharacterOccurrences {
I want to rewrite the code below so it can taking input from a file called String.txt import java.util.*; public class CharacterOccurrences { public static void countOccurrences(Map<Character, Integer> charCounts) { Scanner in = new Scanner(System.in); System.out.print("Enter a string: "); String str = in.nextLine(); char ch; for(int i = 0; i < str.length(); ++i) { ch = str.charAt(i); if(ch >= 'A' && ch <= 'Z') { ch += 32; } if(ch >= 'a' && ch <= 'z') { if(!charCounts.containsKey(ch)) { charCounts.put(ch, 0); } charCounts.put(ch, charCounts.get(ch) + 1); } } } public static void printResults(Map<Character, Integer> charCounts) { ListCharacter, Integer>> list = new ArrayList<>(); for(Map.Entry<Character, Integer> entry: charCounts.entrySet()) { list.add(entry); } Map.Entry<Character, Integer> temp; for(int i = 0; i < list.size(); ++i) { for(int j = 0; j < list.size() - 1; ++j) { if(list.get(j).getKey() > list.get(j + 1).getKey()) { temp = list.get(j); list.set(j, list.get(j + 1)); list.set(j + 1, temp); } } } System.out.println("Map contains: "); System.out.println("Sort by keys"); System.out.println("Key\tValue"); for(int i = 0; i < list.size(); ++i) { System.out.println(list.get(i).getKey() + "\t" + list.get(i).getValue()); } for(int i = 0; i < list.size(); ++i) { for(int j = 0; j < list.size() - 1; ++j) { if(list.get(j).getValue() < list.get(j + 1).getValue()) { temp = list.get(j); list.set(j, list.get(j + 1)); list.set(j + 1, temp); } } } System.out.println("Sort by values "); System.out.println("Key\tValue"); for(int i = 0; i < list.size(); ++i) { System.out.println(list.get(i).getKey() + "\t" + list.get(i).getValue()); } } public static void main(String[] args) { Map<Character, Integer> map = new HashMap<>(); countOccurrences(map); printResults(map); } } Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
