对不起我是Java新手。我正在尝试计算文本文件中每个单词的长度,但是当我打印结果时,我按字母长度存储单词的String数组的每个元素都包含null,我真的不明白。< / p>
import java.awt.List;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
import edu.duke.*;
public class WordLengths {
public static void main(String[] args) {
countWordLengths("/Users/lorenzodalberto/Downloads/ProgrammingBreakingCaesarData/smallHamlet.txt");
}
public static void countWordLengths(String fileName) {
ArrayList<String> myWords = new ArrayList<String>();
String[] wordInd = new String[20];
int[] counts= new int[20];
Scanner sc2 = null;
try {
sc2 = new Scanner(new File(fileName));
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String word = s2.next();
myWords.add(word);
}
}
System.out.println("all of my words " + myWords);
for (String word : myWords) {
word = word.toLowerCase();
int length = word.length();
wordInd[length] += " " + word + " ";
counts[length] += 1;
System.out.println(wordInd[length]);
}
for (int i = 1; i < counts.length; i++) {
int j = counts[i];
if (j > 0) {
System.out.println(j + "\t words of length " + i + " " + wordInd[i]);
}
}
}
}
这是输出:
all of my words [Laer., My, necessaries, are, embark'd., Farewell., And,, sister,, as, the, winds, give, benefit] null laer. null my null necessaries null are null embark'd. null embark'd. farewell. null and, null sister, null my as null are the null laer. winds null and, give null sister, benefit 2 words of length 2 null my as 2 words of length 3 null are the 2 words of length 4 null and, give 2 words of length 5 null laer. winds 2 words of length 7 null sister, benefit 2 words of length 9 null embark'd. farewell. 1 words of length 11 null necessaries
答案 0 :(得分:2)
如果您将字符串添加到null
,则null
会转换为字符串"null"
。例如,null + " hi there"
提供"null hi there"
。
因此,如果wordInd[length]
为空,则执行
wordInd[length] += " " + word + " ";
然后,您将null
连接到一个字符串,为您提供以"null "
开头的字符串。
尝试检查null:
if (wordInd[length]==null) {
wordInd[length] = word;
} else {
wordInd[length] += " "+word;
}
答案 1 :(得分:1)
在Java中初始化数组时,数组的每个空白空间都会填充默认值,具体取决于类型。
由于您正在创建字符串数组,因此数组的每个插槽都将包含一个&#34; null&#34;值。
您的程序正在按照您的要求执行操作:添加空格 - &gt;一个新的字符串 - &gt;它找到的每个新单词的另一个空格。
编辑:NVM,您的问题已经得到解答:)