Answered step by step
Verified Expert Solution
Link Copied!

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Driven Web Sites

Authors: Mike Morrison, Joline Morrison

1st Edition

061901556X, 978-0619015565

More Books

Students also viewed these Databases questions

Question

Ty e2y Evaluate the integral dy

Answered: 1 week ago

Question

=+j Describe an effective crisis management program.

Answered: 1 week ago