if 语句没有在字数统计程序中为我的计数器增加值

if statement not adding value to my counter in word count program

我有一个 java 程序可以读取 txt 文件并计算该文件中的字数。我设置我的程序,以便将从 txt 文件读取的字符串保存为 ArrayList,并且我的变量 word 包含该 ArrayList。我的代码的问题是,我的 if 语句似乎没有在每次检测到字符串中的 space 时向我的 count 变量添加一个值,它似乎只 运行 if 语句一次。我怎样才能让 if 语句找到 space,将 +1 添加到我的计数器值,删除 space,并在单词变量的字符串中查找下一个 space?这是代码:

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

    public class FrequencyCounting
    {
        public static void main(String[] args) throws FileNotFoundException
        {       
            // Read-in text from a file and store each word and its
            // frequency (count) in a collection.
            Scanner inputFile = new Scanner(new File("phrases.txt"));
            String word= " ";
            Integer count = 0;

            List<String> ma = new ArrayList<String>();

            while(

inputFile.hasNextLine()) {
            word = word + inputFile.nextLine() + " ";
        }
        ma.add(word);
        System.out.println(ma);
        if(word.contains(" ")) {
            ma.remove(" ");
            count++;
            System.out.println("does contain");
        }
        else {
            System.out.println("does not contain");
        }
        System.out.println(count);
        //System.out.println(ma);
        inputFile.close();

        // Output each word, followed by a tab character, followed by the
        // number of times the word appeared in the file. The words should
        // be in alphabetical order.
        ;  // TODO: Your code goes here.

    }
}

当我执行该程序时,我得到的变量计数值为 1,并且我从 phrases.txt

中得到了 txt 文件的返回字符串表示形式

phrases.txt 是:

 my watch fell in the water
time to go to sleep
my time to go visit
watch out for low flying objects
great view from the room
the world is a stage
the force is with you
you are not a jedi yet
an offer you cannot refuse
are you talking to me

您的 if 语句不在任何循环内,因此它只会执行一次。

一个更好的方法,可以节省大量的运行时间,就是像你已经做的那样读取每一行,使用 String.split() 方法在空格上分割它,然后添加每个元素使用 ArrayList.addAll() 方法将 String[] 返回到您的列表中(如果该方法存在,否则(可选地,确保容量并)一个一个地添加元素)。

然后用ArrayList.size()方法统计得到元素个数

你的目标是什么?您只想阅读文件并计算单词数吗?

您需要使用 while 循环而不是只 运行 一次的 if 语句。这是做您想做的事的更好方法:

Scanner inputFile = new Scanner(new File("phrases.txt"));
StringBuilder sb = new StringBuilder();
String line;
int totalCount = 0;

while(inputFile.hasNextLine()) {
    line = inputFile.nextLine();
    sb.append(line).append("\n"); // This is more efficient than concatenating strings
    int spacesOnLine = countSpacesOnLine(line);
    totalCount += spacesOnLine;
    // print line and spacesOnLine if you wish to here
}

// print text file
System.out.println(sb.toString());
// print total spaces in file
System.out.println("Total spaces" + totalCount);

inputFile.close();

然后添加一个计算一行空格的方法:

private int countSpacesOnLine(String line) {
    int totalSpaces = 0;
    for(int i = 0; i < line.length(); i++) {
        if (line.charAt(i) == ' ')
            totalSpaces += 1;
    }
    return totalSpaces;
}

您也可以使用以下一种衬垫实现您的 objective:

int words = Files.readAllLines(Paths.get("phrases.txt"), Charset.forName("UTF-8")).stream().mapToInt(string -> string.split(" ").length).sum();

可能我来晚了,但这是c#简单版:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace WhosebugAnswers
{
    class Program
    {
        static void Main(string[] args)
        {

            string contents = File.ReadAllText(@"C:\temp\test.txt");
            var arrayString = contents.Split(' ');
            Console.WriteLine("Number of Words {0}", arrayString.Length);
            Console.ReadLine();
        }
    }
}

根据您代码中的注释:

// Read-in text from a file and store each word and its
// frequency (count) in a collection.
// Output each word, followed by a tab character, followed by the
// number of times the word appeared in the file. The words should
// be in alphabetical order.

我的理解是您需要存储每个单词的计数,而不是单词的总数。为了存储每个应该按字母顺序存储的单词的计数,最好使用 TreeMap。

public static void main(String[] args) {
    Map<String, Integer> wordMap = new TreeMap<String, Integer>();
    try {
        Scanner inputFile = new Scanner(new File("phrases.txt"));
        while(inputFile.hasNextLine()){
            String line = inputFile.nextLine();
            String[] words = line.split(" ");
            for(int i=0; i<words.length; i++){
                String word = words[i].trim();
                if(word.length()==0){
                    continue;
                }
                int count = 0;
                if(wordMap.containsKey(word)){
                    count = wordMap.get(word);
                }
                count++;
                wordMap.put(word, count);
            }
        }
        inputFile.close();
        for(Entry<String,Integer> entry : wordMap.entrySet()){
            System.out.println(entry.getKey()+"\t"+entry.getValue());
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

}