无法读取和存储文本文件中的每一行

问题描述 投票:-1回答:3

我有一个名为“ math.txt的文本文件,其中包含几行数学代码。这些行存储在math.txt中。

1+2+3
1+2+3+4
1+2+3+4+5
1+2+3+4+5+6
1+2+3+4+5+6+7
1+2+3+4+5+6+7+8

我下面的代码应该从文本文件中读出每一行,然后将每一行存储在String数组中。由于某些原因,仅打印某些行,并且似乎只有某些行存储在数组中。

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

class Main {
  public static void main(String[] args) throws IOException {

    //scanner which scans the text file with math equations
    Scanner file = new Scanner (new File("math.txt"));

    //new string array of of infinite size to read every line
    String [] lines = new String [100000];

    //int to count how many lines the text file has to be used in a future for loop
    int lineCount = -1;    


    System.out.println("\nPrint each line from text file");


    //if there is a line after the current line, the line count goes up and line is stored in the initial array
    while (file.hasNextLine()){
        System.out.println(file.nextLine());
        lineCount++;
        lines[lineCount] = file.nextLine();
    }

    System.out.println("\nLines in array");

    for(int i=0;i<lineCount; i++){
        System.out.println(lines[i]);
    }

  }
}

输出应为

Print each line from text file
1+2+3
1+2+3+4
1+2+3+4+5
1+2+3+4+5+6
1+2+3+4+5+6+7
1+2+3+4+5+6+7+8

Lines in array
1+2+3
1+2+3+4
1+2+3+4+5
1+2+3+4+5+6
1+2+3+4+5+6+7
1+2+3+4+5+6+7+8

但是我得到了输出

Print each line from text file
1+2+3
1+2+3+4+5
1+2+3+4+5+6+7

Lines in array
1+2+3+4
1+2+3+4+5+6

我的代码中的问题出在哪里?

java file filereader
3个回答
2
投票

在您的while循环中:

while (file.hasNextLine()){
        System.out.println(file.nextLine());
        lineCount++;
        lines[lineCount] = file.nextLine();
    }

您两次调用file.nextLine()。这意味着对于每个存储,将读取两次行。您需要的是这样的东西:

while( file.hasNextLine()) {
    String s = file.nextLine();
    System.out.println(s);
    lines[lineCount++] = s;
}

也从0而不是-1开始您的lineCount;


1
投票

看看您的while块:

while (file.hasNextLine()){
    System.out.println(file.nextLine());
    lineCount++;
    lines[lineCount] = file.nextLine();
}

您看到您两次使用file.nextLine()吗?每个对nextLine()的调用都会使光标前进,因此,当您打算使用当前行两次时,对nextLine()的第二个调用将跳至下一行。

您应该做的是将行存储在本地字段中,然后直接使用该字段。

while (file.hasNextLine()){
    String foo = file.nextLine();
    System.out.println(foo);
    lineCount++;
    lines[lineCount] = foo;
}

1
投票

之所以会出现此问题,是因为您在每次循环迭代中都读取2行。每个

file.nextLine()

正在读取文件中的另一行。

您可以尝试使用此方法:

 while (file.hasNextLine()){
    lineCount++;
    lines[lineCount] = file.nextLine();
    System.out.println(lines[lineCount]);
 }
© www.soinside.com 2019 - 2024. All rights reserved.