Подсчет количества символов из текстового файла - PullRequest
1 голос
/ 26 июля 2011

В настоящее время у меня есть следующий код:

public class Count {

    public static void countChar() throws FileNotFoundException {
        Scanner scannerFile = null;

        try {
            scannerFile = new Scanner(new File("file"));
        } catch (FileNotFoundException e) {
        }

        int starNumber = 0; // number of *'s

        while (scannerFile.hasNext()) {
            String character = scannerFile.next();
            int index =0;
            char star = '*';
            while(index<character.length()) {

                if(character.charAt(index)==star){
                    starNumber++;
                }
                index++;
            }
            System.out.println(starNumber);
        }
    }

Я пытаюсь выяснить, сколько раз * встречается в текстовом файле.Например, для текстового файла с именем Hi * My * name *

метод должен возвращать 3

. В настоящее время происходит то, что происходит с приведенным выше примером, метод возвращает:

0 1 1 2 2 3

Заранее спасибо.

Ответы [ 4 ]

3 голосов
/ 26 июля 2011

Используйте Apache commons-io для чтения файла в строку

String org.apache.commons.io.FileUtils.readFileToString(File file);

А затем используйте Apache commons-lang для подсчета совпадений *:

int org.apache.commons.lang.StringUtils.countMatches(String str, String sub)

Результат:

int count = StringUtils.countMatches(FileUtils.readFileToString(file), "*");
2 голосов
/ 26 июля 2011

Все в вашем методе работает нормально, за исключением того, что вы печатаете счетчик на строку:

    while (scannerFile.hasNext()) {
        String character = scannerFile.next();
        int index =0;
        char star = '*';
        while(index<character.length()) {

            if(character.charAt(index)==star){
                starNumber++;
            }
            index++;
        }
        /* PRINTS the result for each line!!! */
        System.out.println(starNumber);
    }
2 голосов
/ 26 июля 2011
int countStars(String fileName) throws IOException {
    FileReader fileReader = new FileReader(fileName);
    char[] cbuf = new char[1];
    int n = 0;

    while(fileReader.read(cbuf)) {
        if(cbuf[0] == '*') {
            n++;
        }
    }
    fileReader.close();
    return n;
}
0 голосов
/ 26 июля 2011

На этом этапе я бы придерживался библиотек Java, а затем использовал бы другие библиотеки (например, библиотеки commons), когда вы ближе познакомитесь с основным API Java. Это не в моей голове, возможно, нужно настроить для запуска.

StringBuilder sb = new StringBuilder();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);

String s = br.readLine();
while (s != null)
{
  sb.append(s);
  s = br.readLine();
}
br.close(); // this closes the underlying reader so no need for fr.close()

String fileAsStr = sb.toString();
int count = 0;
int idx = fileAsStr('*')
while (idx > -1)
{
  count++;
  idx = fileAsStr('*', idx+1);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...