So I have a piece of code below that loads in a text file and analyzes it to show the percentages of each letter from a word or sentence that's stored within a text file.
Instead of using char []
letters, I want to be able to use ASCII
code instead.
I am unsure how to go about doing this so any help would be appreciated!
This is the code I have so far:
import java.io.File;
import java.util.Scanner;
public class testing {
@SuppressWarnings("resource")
public static void main(String[] args){
Scanner scan;
try {
scan = new Scanner(new File("G:/test.txt")); //change directory to load in text file
}
catch (Exception e) {
System.out.println("File was not found ");
return;
}
int[] count = new int[26];
int total = 0;
while(scan.hasNextLine()) {
String text2 = scan.nextLine();
System.out.println ("\n--------------------------------------------------------------------------------------------------------");
System.out.println (" Words loaded in from the file: " + text2);
System.out.println ("--------------------------------------------------------------------------------------------------------");
System.out.print("\n");
System.out.print("");
char[] letters = text2.toCharArray();
char[] letters1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n','o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
for(int i = 0; i < letters.length; i++) {
for(int j = 0; j < 26; j++) {
if(letters[i] == letters1[j]) {
count[j]++;
total = total + 1;
break;
}
}
}
for (int i = 0; i < 26; i++){
System.out.format("| "+ letters1[i]+" ");
}
System.out.println ("\n----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
for (int i = 0; i < 26; i++){
float percentage = 0;
if (count[i] > 0)
percentage = ((float) count[i]/total)*100;
System.out.format("| "+percentage+ "%% ");
}
}
}
}