2017-06-13 61 views
0

對不起。我是Java新手。我試圖計算文本文件中每個單詞的長度,但是當我打印結果時,按長度存儲單詞的字符串數組中的每個元素都包含一個空值,而且我真的不理解它。String數組的每個元素都包含空值

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

對象數組填充null。在使用它之前,您需要將實際的字符串放在wordInd中。 – matt

回答

2

如果添加一個字符串null,該null被轉換成字符串"null"。例如,null + " hi there"給出"null hi there"

所以,如果wordInd[length]是空的,你執行

wordInd[length] += " " + word + " "; 

然後你被串聯null爲一個字符串,讓您開始"null "的字符串。

嘗試檢查空:

if (wordInd[length]==null) { 
    wordInd[length] = word; 
} else { 
    wordInd[length] += " "+word; 
} 
+0

非常感謝,解決了這個問題!我會投你一票,但我沒有聲望 – costep

0

當初始化Java中的數組,數組的每一個空的空間充滿取決於類型的默認值。

由於您正在創建字符串數組,因此數組中的每個插槽都將包含一個「空」值。

您的程序正在執行您要求的操作:爲找到的每個新單詞添加一個空格 - >一個新的字符串 - >另一個空格。

編輯:NVM,你的問題已經被回答:)

相關問題