Разбор текстового файла и подсчет вхождений шаблонов с несколькими циклами с использованием класса Scanner

Я использую несколько циклов while со сканером, у меня есть оба цикла while, работающие до такой степени, что, какой бы ни был один перед другим, он вычислит правильные результаты, однако приведенные ниже циклы while будут нарушены.

Я попытался добавить разрыв; в обоих, но это не поможет. Что я делаю неправильно?

 public static void main(String args[]) throws IOException {

    Scanner sc = new Scanner(Coursework.class.getResourceAsStream("test.txt")).useDelimiter(("[^A-Za-z']+"));

    int count = 0;
    int numberOfLines = 0;
    int numberOfConsonants = 0;
    int numberOfPunctuation = 0;
    double average = 0;
    int numberOfWords = 0;
    int numberOfChars = 0;

    String x = "";
    String nextLine = "";

        while (sc.hasNextLine()) {
            nextLine = sc.nextLine();
            numberOfLines++;
            x = nextLine.toLowerCase().trim();
            for (int i = 0, n = x.length(); i < n; i++) {
                char c = x.charAt(i);
                numberOfChars++;
                if ((c == 'b' || c == 'c' || c == 'd' ||
                     c == 'f' || c == 'g' || c == 'h' ||               
                     c == 'j' || c == 'k' || c == 'l' || 
                     c == 'm' || c == 'n' || c == 'p' || 
                     c == 'q' || c == 'r' || c == 's' || 
                     c == 't' || c == 'v' || c == 'w' ||
                     c == 'x' || c == 'y' || c == 'z')) {
                        numberOfConsonants++;

                }
                if ((c =='?'| c == '.' || c == ',' || c == '"')){
                    numberOfPunctuation++;
                }
            }
       }

       while (sc.hasNext()) {
            sc.next();
            count++; 
       }
}

2 ответа

Попробуйте изменить количество переменных и количество строк на 1.

Я не уверен, что требуется для вашего назначения или какой части языка Java он был сосредоточен на том, чтобы вы выучили, но если бы я хотел аналогичным образом проанализировать и подсчитать входной файл, я бы, вероятно, сделал что-то вроде следующего:

Где file.txt содержит:

1. Aaaaa eiou foo!
2. bbbbb?    

И программа была скомпилирована и запущена следующим образом:

javac TextAnalyzer.java
java TextAnalyzer file.txt

Выход:

Text Analysis of file: file.txt

 characters:  27
 words:       6
 uppercase:   1
 lowercase:   16
 consonants:  7
 vowels:      11
 digits:      2
 punctuation: 4
 whitespace:  4

Вот исходный код:

import java.io.*;
import java.util.*;
import java.util.regex.*;

public class TextAnalyzer {

    public static int count(String line, Pattern pattern) {
        int count = 0;
        Matcher matcher = pattern.matcher(line);
        while (matcher.find()) {
            ++count;
        }
        return count;
    }

    public static void main(String args[]) throws IOException {

        Pattern vowels      = Pattern.compile("[aeiouAEIOU]");
        Pattern consonants  = Pattern.compile("[bcdfghjklmnpqrstuvwxyzBCDFGHJKLMNOPQRSTUVWXYZ]");
        Pattern punctuation = Pattern.compile("\\p{Punct}");
        Pattern whitespace  = Pattern.compile("\\p{Space}");
        Pattern digits      = Pattern.compile("\\p{Digit}");
        Pattern uppercase   = Pattern.compile("\\p{Upper}");
        Pattern lowercase   = Pattern.compile("\\p{Lower}");
        Pattern words       = Pattern.compile("\\w+");
        Pattern characters  = Pattern.compile(".");

        int vowelCount       = 0;
        int consonantCount   = 0;
        int punctuationCount = 0;
        int whitespaceCount  = 0;
        int digitCount       = 0;
        int uppercaseCount   = 0;
        int lowercaseCount   = 0;
        int wordCount        = 0;
        int charCount        = 0;
        int lineCount        = 0;

        if (args[0].length() == 0) {
            System.out.println("Error: No filename provided");
            System.exit(-1);
        }

        try {
            BufferedReader br = new BufferedReader(new FileReader(args[0]));
            for (String line; (line = br.readLine()) != null; ) {
                ++lineCount;
                vowelCount       += count(line, vowels);
                consonantCount   += count(line, consonants);
                punctuationCount += count(line, punctuation);
                whitespaceCount  += count(line, whitespace);
                digitCount       += count(line, digits);
                uppercaseCount   += count(line, uppercase);
                lowercaseCount   += count(line, lowercase);
                wordCount        += count(line, words);
                charCount        += count(line, characters);
            }
        } catch (Exception e) {
            System.out.println("Couldn't parse " + args[0] + "\n" + e.getMessage());
            System.exit(-1);
        }

        System.out.println("Text Analysis of file: " + args[0]);
        System.out.println("");
        System.out.println(" characters:  "  + charCount);
        System.out.println(" words:       "  + wordCount);
        System.out.println(" uppercase:   "  + uppercaseCount);
        System.out.println(" lowercase:   "  + lowercaseCount);
        System.out.println(" consonants:  "  + consonantCount);
        System.out.println(" vowels:      "  + vowelCount);
        System.out.println(" digits:      "  + digitCount);
        System.out.println(" punctuation: "  + punctuationCount);
        System.out.println(" whitespace:  "  + whitespaceCount);
    }
}
Другие вопросы по тегам