2014-10-22 81 views
0

我正在读取文件并将其复制到数组中。我的文件有五行文字,每句都有一个句子。我得到我的输出“数组大小是5”,但之后没有。如果我添加了阵列的打印线,它会给我5个空值...从文本文件读入数组 - 获取“空值”

有人可以帮助解释我做错了什么吗?谢谢!

public static int buildArray() throws Exception 
 
    { 
 
     System.out.println("BuildArray is starting "); 
 
    
 
     java.io.File textFile; // declares a variable of type File 
 
     textFile = new java.io.File ("textFile.txt"); //reserves the memory 
 
     
 
     Scanner input = null; 
 
      try 
 
      { 
 
       input = new Scanner(textFile); 
 
      } 
 
      catch (Exception ex) 
 
      { 
 
       System.out.println("Exception in method"); 
 
       System.exit(0); 
 
      } 
 

 
      int arraySize = 0; 
 
      while(input.hasNextLine()) 
 
       { 
 
        arraySize = arraySize + 1; 
 
        if (input.nextLine() == null) 
 
         break; 
 
       } 
 
     System.out.println("Array size is " + arraySize); 
 

 
     // Move the lines into the array 
 
     String[] linesInRAM = new String[arraySize];// reserve the memory 
 
     int count = 0; 
 
     if (input.hasNextLine()) 
 
      { 
 
       while(count < arraySize) 
 
       { 
 
        System.out.println("test"); 
 
        linesInRAM[count] = input.nextLine(); 
 
        System.out.println(linesInRAM[count]); 
 
        count = count + 1; 
 
       } 
 
      }

+3

你永远不会重置扫描仪,所以它直到在文件的结尾... – MadProgrammer 2014-10-22 02:50:46

回答

0

在这段代码

int count = 0; 
    if (input.hasNextLine()) 

以上hasNextLine将永远是假的,你已经阅读过该文件的所有道路。

将扫描仪重置为文件的开头,或使用动态列表,例如ArrayList添加元素。

0

我的Java有点生疏,但我的答案的基本要点是您应该创建一个新的Scanner对象,以便它再次从文件的开头读取。这是“重置”到最开始的最简单方法。

你的代码是目前没有工作,因为当你调用input.nextLine()你实际上是增加了扫描仪,因此在第一次while()input结束时坐在文件的末尾,所以当你再次调用它input.nextLine()返回null

Scanner newScanner = new Scanner(textFile); 

然后在你的代码的底部,你的循环应该是这样的,而不是:

if (newScanner.hasNextLine()) 
    { 
     while(count < arraySize) 
      { 
       System.out.println("test"); 
       linesInRAM[count] = newScanner.nextLine(); 
       System.out.println(linesInRAM[count]); 
       count = count + 1; 
      } 
    } 
+0

这是正是我需要的,谢谢你,谢谢。现在它正在工作。我不太清楚扫描仪是这样工作的,谢谢你的解释! – gerii 2014-10-22 05:24:26

+0

当然!确保点击该复选标记和/或向上箭头;) – yiwei 2014-10-22 14:53:04