简体   繁体   English

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

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

I have a java program that reads a txt file and counts the words in that file. 我有一个Java程序,该程序读取txt文件并计算该文件中的单词。 I setup my program so the String read from the txt file is saved as an ArrayList, and my variable word contains that ArrayList. 我设置了程序,以便将从txt文件读取的字符串另存为ArrayList,而我的可变字包含该ArrayList。 The issue with my code is that my if statement does not seem to add a value to my count variable each time it detects space in the word string, it seems to only run the if statement once. 我的代码的问题在于,我的if语句似乎每次检测到单词字符串中的空格时都不会向我的count变量添加值,它似乎只运行一次if语句。 How can I make it so the if statement finds a space, adds a +1 to my counter value, removes the space, and looks for the next space in the word variable's string? 我该如何做,以便if语句找到一个空格,在我的计数器值上添加+1,删除该空格,并在word变量的字符串中查找下一个空格? Here is the code: 这是代码:

       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.

    }
}

When I execute the program, I get a value of 1 for the variable count and I get a returned string representation of the txt file from my phrases.txt 当我执行程序时,变量计数的值为1,并且从我的pussy.txt中获得了txt文件的返回字符串表示形式。

phrases.txt is : pussy.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

Your if statement is not inside any loop, so it will only execute once. 您的if语句不在任何循环内,因此它将仅执行一次。

A better approach, which would save a shit ton of runtime, is to read each line like you already do, use the String.split() method to split it on spaces, then add each element of the returned String[] to your list by using the ArrayList.addAll() method (if that one exist, otherwise (optionally, ensure the capacity and) add the elements one by one). 一种更好的方法可以节省大量的运行时间,就像您已经读过的那样,读取每一行,使用String.split()方法将其拆分为空格,然后将返回的String []的每个元素添加到列表中通过使用ArrayList.addAll()方法(如果存在),否则(可选地,确保容量并)将元素一一添加。

Then count by using the ArrayList.size() method to get the number of elements. 然后使用ArrayList.size()方法计数以获取元素数量。

What is your goal here ? 您在这里的目标是什么? Do you just want to read the file and count numbers of words? 您是否只想读取文件并计算单词数?

You need to use a while loop instead of an if statement that'll just run once. 您需要使用while循环,而不是只会运行一次的if语句。 Here's a better way to do what you want to do: 这是做您想做的更好的方法:

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();

Then add a method that counts the spaces on a line: 然后添加一种方法来计算一行上的空格:

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

您也可以使用以下一种衬垫来实现您的目标:

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

probably I am late, but here is c# simple version: 可能我来晚了,但是这里是c#简单版本:

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

namespace StackOverflowAnswers
{
    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();
        }
    }
}

Based on the comments in your code : 根据您代码中的注释:

// 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.

My understanding is that you need to store count for every word, rather having a total count of words. 我的理解是,您需要存储每个单词的计数,而不是总单词数。 For storing count for every word which should be stored itself in alphabetical order, it is better to go with a TreeMap. 为了存储应该按字母顺序存储的每个单词的计数,最好使用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();
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM