大多数时候它都能正常工作。很少会倒数一。有什么猜测吗?
public static int countWords(File file) throws FileNotFoundException, IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
List<String> strList = new ArrayList<>();
while ((line=br.readLine())!=null){
String[] strArray= line.split("\\s+");
for (int i=0; i<strArray.length;i++){
strList.add(strArray[i]);
}
}
return strList.size();
}
特别是在下面的示例中,它给出了 3 而不是 2:
\n
k
最佳答案
我猜第二行被分成两个字符串,“”和“k”。请参阅下面的代码:
import java.util.Arrays;
public static void main(String[] args) {
String str = " k";
String[] array = str.split("\\\s+");
System.out.println("length of array is " + array.length); // length is 2
System.out.println(Arrays.toString(array)); //array is [, k]
}
关于java - 为什么我的单词计数器有时会减一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37267543/