我正在尝试计算ArrayList包含的单词数。如果每个单词都在一个单独的行上,我知道怎么做,但有些单词在同一行,如:
hello there
blah
cats dogs
所以我想我应该浏览每个条目并以某种方式找出当前条目包含的单词数,例如:
public int numberOfWords(){
for(int i = 0; i < arraylist.size(); i++) {
int words = 0;
words = words + (number of words on current line);
//words should eventually equal to 5
}
return words;
}
我在想什么?
答案 0 :(得分:5)
您应该在循环之外声明并实例化int words
,在循环的每次迭代期间int
都不会重新分配。您可以使用for..each
语法循环遍历列表,这将消除列表中get()
个项目的需要。要将split
String
行中的多个字处理为Array
,并计算Array
中的项目。
public int numberOfWords(){
int words = 0;
for(String s:arraylist) {
words += s.split(" ").length;
}
return words;
}
完整测试
public class StackTest {
public static void main(String[] args) {
List<String> arraylist = new ArrayList<String>();
arraylist.add("hello there");
arraylist.add("blah");
arraylist.add(" cats dogs");
arraylist.add(" ");
arraylist.add(" ");
arraylist.add(" ");
int words = 0;
for(String s:arraylist) {
s = s.trim().replaceAll(" +", " "); //clean up the String
if(!s.isEmpty()){ //do not count empty strings
words += s.split(" ").length;
}
}
System.out.println(words);
}
}
答案 1 :(得分:1)
应该是这样的:
public int numberOfWords(){
int words = 0;
for(int i = 0; i < arraylist.size(); i++) {
words = words + (number of words on current line);
//words should eventually equal to 5
}
return words;
}
答案 2 :(得分:0)
我认为这可以帮到你。
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
public class LineWord {
public static void main(String args[]) {
try {
File f = new File("C:\\Users\\MissingNumber\\Documents\\NetBeansProjects\\Puzzlecode\\src\\com\\test\\test.txt"); // Creating the File passing path to the constructor..!!
BufferedReader br = new BufferedReader(new FileReader(f)); //
String strLine = " ";
String filedata = "";
while ((strLine = br.readLine()) != null) {
filedata += strLine + " ";
}
StringTokenizer stk = new StringTokenizer(filedata);
List <String> token = new ArrayList <String>();
while (stk.hasMoreTokens()) {
token.add(stk.nextToken());
}
//Collections.sort(token);
System.out.println(token.size());
br.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
因此,在这种情况下,您将从文件中删除数据,并在对它们进行标记后将它们存储在列表中,只需计算它们,如果您只想从控制台获取输入,请使用Bufferedreader,标记它们,用空格分隔,放入列表,简单获取大小。
希望你得到你想要的东西。