为什么我得到" null"作为输出字符串? Java的

时间:2015-04-07 03:53:41

标签: java file null

我要做的是从文件中读取(在这种情况下,文件包含超过100,000行)并将值存储在数组中,然后打印出前10行。然而,当我运行程序时,我得到第一行,然后是9行" null"这显然不是我想要的!这是代码,任何提示将不胜感激。

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

2 个答案:

答案 0 :(得分:4)

int i = 0;循环之外定义while。每次循环运行时它都会设置为零。这就是问题所在。

答案 1 :(得分:0)

你在while循环中犯了错误。您必须在while循环之前定义'int i = 0'。在你的情况下,发生的是每当while循环执行时,i被初始化为0.即每次找到所需长度的单词时,该单词将被存储在数组[0]中(因为我每次迭代都被初始化为0) of while循环)替换先前存储的值。因此,您只获得第一个值并保持显示为null,因为在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
    }
}