java - 使用 ArrayList 和循环计算文本文件中的标点符号无法正常工作,如何解决?

标签 java loops arraylist

已解决。

我正在尝试计算文本文件中有多少个标点符号。我正在使用 if 语句来计算每个标点符号的数量,但似乎没有用,它说每个元素都是一个句号。

这是我的循环

    for (int c = 0; c <= punk1.size()-1; c++) {
        if (punk1.get(c).matches(".")) {
            fullstop += 1;
        } else if (punk1.get(c).matches(",")) {
            comma += 1;
        } else if (punk1.get(c).matches("?")) {
            qmark += 1;
        } else if (punk1.get(c).matches("!")) {
            expoint += 1;
        } else if (punk1.get(c).matches("\"")) {
            doublequote += 1;
        } else if (punk1.get(c).matches("\'")){
            singlequote += 1;
        } else {
            System.out.println("Punctuation Marks not Found");
        }
    }

这是输出。

Punctuation marks in text file: [., ., ., ,, ,, ,, !, !, !, ?, ?, ?, ", ",", ', ', ']
Number of Punctuation marks in file: 18
Number of fullstops: 18
Number of commass: 0 
Number of question marks: 0 
Number of exclamation point: 0 
Number of double quotes: 0 
Number of singlequotes: 0

每个应该有 3 个。

最佳答案

您正在使用使用正则表达式匹配的 matches。自从 '。'如果条件始终为真,则首先匹配任何字符。

关于java - 使用 ArrayList 和循环计算文本文件中的标点符号无法正常工作,如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32065562/

相关文章:

java - java中的字符串排序

python - 在 utf8 中迭代两个数据帧的列和 str.encode

java - 编辑ArrayList(Java Swing/GUI)中的对象

java - 如何将 Vector 更改为 ArrayList?

Java运行时问题,但是构建项目没有错误

java - 如何使用 BufferedReader 将 String 添加到 ArrayList 中?

java - BouncyCaSTLe openssl无法解决

bash - while循环后的左尖括号在bash中意味着什么?

C 字符串比较

java - 同步ArrayList并发写入