Question: Java I want the program to be edited so that The user will manually enter a string, then the text file name, and it will
Java
I want the program to be edited so that The user will manually enter a string, then the text file name, and it will then enter the string into the text file as well as the output the results.
I have already written this program that counts the number of occurences of each letter in a string. The program displays the letters in ascending order, by keys and by value. It asks for a text file, which for example, contains the lines:
Welcome to CECS
Java Programming
With this text file the output will be:
Map contains:
Sort by keys
Key Value
2 1
7 2
a 3
c 3
e 3
g 2
i 1
j 1
l 1
m 3
n 1
o 3
p 1
r 2
s 1
t 1
v 1
w 1
Sort by values
Key Value
o 3
m 3
e 3
c 3
a 3
7 2
r 2
g 2
w 1
v 1
t 1
s 1
2 1
p 1
n 1
l 1
j 1
i 1
THis is what I have so far:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.Map.Entry;
public class MapSorting {
private static Scanner read;
public static void sortByKey(Map
System.out.println("Sort by keys");
System.out.println("Key\tValue");
Map
Iterator
while(itr.hasNext()) {
Entry
System.out.println(entry.getKey()+"\t"+entry.getValue());
}
}
public static void sortByValue(Map
System.out.println("Sort by values");
System.out.println("Key\tValue");
List
Comparator
public int compare(Entry
return object1.getValue().compareTo(object2.getValue());
}
};
Collections.sort(list, comparator);
for(int i=list.size()-1;i>=0;i--) {
Entry
System.out.println(entry.getKey()+"\t"+entry.getValue());
}
}
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the text file to read from:");
String fileName = scanner.nextLine();
File file = new File(fileName);
if(file.exists()) {
read = new Scanner(file);
String line = "";
while(read.hasNextLine()) {
line = line + read.nextLine().toLowerCase();
}
char c;
Map
for(int i=0;i c = line.charAt(i); if(c==' ') { continue; } if(map.containsKey(c)) { map.put(c, map.get(c)+1); }else { map.put(c, 1); } } System.out.println("Map contains:"); sortByKey(map); sortByValue(map); scanner.close(); } else { System.out.println("File does not exist"); } } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
