I want to write a program that reads a text from a file character by character and counts how frequently each character occurs.
I have the following code:
import java.util.Scanner;
import java.io.*;
public class text {
public static void frequency (char[] array, int k)
{
int ok=0;
for (char i ='a'; i<='z'; i++)
{
ok=0;
for (int j=0; j<k; j++)
if (i==array[j])
ok++;
if (ok!=0)
{
System.out.println (i + " appears for " + ok + " times");
}
}
}
public static void main(String[] args)
throws FileNotFoundException {
Scanner in = new Scanner(new File("C:\\Users\\Diana\\workspace\\Text\\src\\FileInput"));
char[] array = new char [100];
int k=0;
while (in.hasNext())
{
array[k] = in.next().charAt(k);
k++;
}
for (int i=0; i<k; i++)
System.out.print (array[i]);
in.close();
frequency (array, k);
}
}
The problem is that it doesn't read all the values from my file. If I have for example Good Morning it only reads Go. Any ideas what I'm doing wrong?