2015-04-07 64 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 
    } 
} 
相关问题