Answered step by step
Verified Expert Solution
Question
1 Approved Answer
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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started