2

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?

1 Answer 1

6

Look at your loop:

while (in.hasNext())
{
    array[k] = in.next().charAt(k);
    k++;
}

This reads one token at a time, and takes the kth character from that token. So from "Good Morning" it retrieves character 0 of "Good" (G) and character 1 of "Morning" (o).

It's not clear why you've got k at all, to be honest - but if you just want to read a file into a character array, it's worth using a Reader instead - or Files.readAllLines if you're using Java 7 or later. For example:

List<String> lines = Files.readAllLines(Paths.get("FileInput"));
StringBuilder builder = new StringBuilder();
for (String line : lines) {
    builder.append(line);
}
char[] array = builder.toString().toCharArray();

(This will skip the line break characters, but that's probably what you want.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.