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

Unable to read and store each line from a text file

我有一个名为“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

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

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

我的代码哪里出了问题?

看看你的 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;
}

在你的 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;

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

file.nextLine()

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

你可以试试这个:

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