[英]if statement not adding value to my counter in word count program
我有一个Java程序,该程序读取txt文件并计算该文件中的单词。 我设置了程序,以便将从txt文件读取的字符串另存为ArrayList,而我的可变字包含该ArrayList。 我的代码的问题在于,我的if语句似乎每次检测到单词字符串中的空格时都不会向我的count变量添加值,它似乎只运行一次if语句。 我该如何做,以便if语句找到一个空格,在我的计数器值上添加+1,删除该空格,并在word变量的字符串中查找下一个空格? 这是代码:
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,并且从我的pussy.txt中获得了txt文件的返回字符串表示形式。
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
您的if语句不在任何循环内,因此它将仅执行一次。
一种更好的方法可以节省大量的运行时间,就像您已经读过的那样,读取每一行,使用String.split()方法将其拆分为空格,然后将返回的String []的每个元素添加到列表中通过使用ArrayList.addAll()方法(如果存在),否则(可选地,确保容量并)将元素一一添加。
然后使用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;
}
您也可以使用以下一种衬垫来实现您的目标:
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 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();
}
}
}
根据您代码中的注释:
// 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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.