2015-04-07 98 views
0

我想要做的是從文件中讀取(在這種情況下,文件包含超過100,000行)並將值存儲在數組中,然後打印出前10行。但是,當我運行程序時,我得到第一行,然後是9行「null」,這顯然不是我想要的!這是代碼和任何提示將不勝感激。爲什麼我會將「null」作爲輸出字符串? Java

import java.io.*; 
import java.util.Scanner; 

public class DawsonZachA5Q2{ 
    public static void main(String[] args){ 

Scanner keyboard = new Scanner(System.in); 

System.out.println("Enter a size for the number of letters for words: "); 
int size = keyboard.nextInt();//prompts user for input 
String[] array = new String[27000]; 

    try { 
     File file = new File("big-word-list.txt"); 
     Scanner scanner = new Scanner(file); 


     // Start a line count and declare a string to hold our current line. 
     int linecount=0; 

     // Tells user what we're doing 
     System.out.println("Searching for words with " + size + " letters in file..."); 
     int wordCount=0; 

     while (scanner.hasNext()){ 
      int i = 0; 
      String word = scanner.next(); 

      if(size == word.length()){ 
      wordCount++; 
      array[i]=word; 
      i++; 
      //add word to array 
      // increase the count and find the place of the word 
     } 
     } 

     linecount++; 






      System.out.println(wordCount); 

      System.out.println(wordCount+" words were found that have "+size+ " letters.");//final output 


      for(int o = 0; o<10; o++){ 
      System.out.println(array[o]); 
      } 


     scanner.close(); 
    }// our catch just in case of error 
    catch (IOException e) { 
     System.out.println("Sorry! File not found!"); 
    } 



    } // main 


} // class 
+4

我會讓你自己想出這一個。就在'array [i] = word;'之前,添加這一行:'System.out.println(「關於在索引處設置數組」+ i);'。然後看看會發生什麼。 – ajb

+0

啊,是的,我明白你在說什麼了,謝謝! – Zhdawson

回答

4

定義int i = 0;while循環。每次循環運行時它都被設置爲零。這是這裏的問題。

0

您誤入while循環。你必須在while循環之前定義'int i = 0'。在你的情況下,發生什麼是每當while循環執行,我被初始化爲0.即每次,找到所需長度的單詞,該單詞將存儲在數組[0](因爲我每次迭代初始化爲0 while循環)替換之前存儲的值。結果,你只能得到第一個值並且其餘顯示爲空,因爲在array [1]之後沒有任何東西被存儲。 因此,實際流量應該是這樣的。

// i is initialized outside of loop. 
int i = 0; 
while (scanner.hasNext()){ 
    //int i = 0; this is your error 
    String word = scanner.next(); 
    if(size == word.length()){ 
     wordCount++; 
     array[i]=word; 
     i++; 
     //add word to array 
     // increase the count and find the place of the word 
    } 
} 
相關問題