【发布时间】:2019-12-08 18:43:44
【问题描述】:
我有一个名为“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
我的代码哪里出了问题?
【问题讨论】:
-
file.nextLine() 使用了两次 System.out.println(file.nextLine());一个用于 file.nextLine();所以行被跳过了。
-
对
nextLine()的每次调用都将完全消耗并从文件中返回一行。您调用它两次而不是每次迭代一次。因此,您读取并打印一行,然后读取并存储另一行。每次迭代的第一行永远不会被存储。 -
所以我只能将while循环用于一个函数?一个用于存储,一个用于打印?
标签: java file filereader