So, ive had this problem before, but I cant seem to find the culprit this time. Its a really large project I have to do and I'm stuck on the first part. So for now, we'll just say that all its supposed to do is count how many times a letter occurs in a sentence. But all that comes out is zeros! Take a look and respond if you catch whats wrong!
This is the actual class.
import java.util.*; import java.io.*; public class FrequencyAnalysis { //private Scanner in = new Scanner(new File("Sub.txt")); private Scanner in; private int lets = 0; private int[] occurance = new int[26]; private String file = ""; private String[] alph = {"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"}; public FrequencyAnalysis (Scanner in) { this.in = in; } public int countLetters() //counts the number of letters in the file { for (int i = 0; this.in.hasNext(); i++) { String s = this.in.next(); lets += s.length(); } return lets; } public String getSent() //makes a string of the files text and takes away all the spaces and punctuation, while making the letters all lowercase. { for (int i = 0; this.in.hasNext(); i++) { file += this.in.next(); } return file.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); } public int[] getOccurance(String file) //counts how many times a letter occurs in the String. { for (int i = 0; file.length() != 0; i ++) { int c = 0; while (c < 26) { if (alph[c].equals(file.substring(0, 1))) { occurance[c] += 1; file = file.substring(1); c = 0; } else { c++; } } } return occurance; } }
And this is the tester I was using. Note: If you want to run it yourself, you will have to get a file named "Sub.txt" and put words in it. PS: I used BluJay for the compiler.
import java.util.*; import java.io.*; public class FrequencyTester { public static void main(String [] args) throws IOException { Scanner in = new Scanner(new File ("Sub.txt")); FrequencyAnalysis obj = new FrequencyAnalysis(in); obj.countLetters(); for (int i : obj.getOccurance(obj.getSent())) System.out.println(i); } }