Question
Q-Write a Java program that inputs a document and then outputs a bar-chart plot of the frequencies of each alphabet character that appears within that
Q-Write a Java program that inputs a document and then outputs a bar-chart plot of the frequencies of each alphabet character that appears within that document.?
(Can you please solve the file part and explain how to do it because when I run the code it tell me to enter the file name but when I enter it the output is does not exist )
----------------------------------------------------------------------------------------------------------------------------------------
package part_2;
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner;
public class barChart { public static void main(String args[]) throws FileNotFoundException, IOException {
Scanner input = new Scanner(System.in); // Taking the input for the filename System.out.println("Enter the File Name: "); String filename = input.nextLine(); File file = new File(filename); // IF file doesn't exist then print File Doesn't exist and close the program if (!file.exists()) { System.out.println("File Doesn 't Exist"); } else { // Variable to store the data read from file String data = ""; // Using scanner to read data from file input = new Scanner(file);
// Reading data from file while (input.hasNextLine()) { data += input.nextLine(); } // Using hashmap to store character and their count HashMap charCount = new HashMap(); // Changing the data to character array char[] dataArray = data.toCharArray(); // Traversing through the data array and adding it to hash map for (char c : dataArray) { // If character already exits in the hash map increment the count by 1 if (charCount.containsKey(c)) charCount.put(c, charCount.get(c) + 1); // else add the character and initialise the count to 1 else charCount.put(c, 1); } // Traversing through each entry of the map for printing bar chart for (Map.Entry entry : charCount.entrySet()) { // Printing the character System.out.print(entry.getKey() + ":"); // Inner loop for printing the X for number of occurences for (int i = 0; i < (int) entry.getValue(); i++) { System.out.print("X"); } System.out.println(); } } } }
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