我无法读取 .txt 中的所有数字
I can't read all the numbers in a .txt
我正在尝试对包含 1000 万个数字的文件进行平均,每行一个数字。我创建了一个名为 getAverage() 的方法,returns 是一个双精度值。这是代码:
public double promedioDouble() throws IOException
{
double adder = 0;
int counter = 0;
try{
file = new FileReader(filePath);
reader = new BufferedReader(file);
while(reader.readLine()!=null)
{
adder+=Double.parseDouble(reader.readLine());
counter++;
}
}
catch (IOException e)
{
System.out.println("cant read");
}
finally {
if (file != null) file.close();
}
return adder/counter;
}
我打印了计数器,它显示了 5.000.000,我不知道为什么 reader 无法读取文件中包含的 1000 万数字,它只读取了一半。我需要这方面的帮助。
您调用了 readLine
两次 - 并忽略了在 while
条件下返回的行。
试试看:
String line;
while( (line = reader.readLine()) !=null)
{
adder+=Double.parseDouble(line);
counter++;
}
您也可以使用 Streams 执行此操作(并尝试使用资源 - 避免需要 finally
):
try (Stream<String> stream = Files.lines(Paths.get(fileName)))
{
stream.forEach(s -> {adder+=Double.parseDouble(s); counter++;});
} catch (IOException e) {
e.printStackTrace();
}
我的回答离你的问题有点远。如果您使用的是 Java 8,您可以通过以下方式快速执行此操作:
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
return stream.mapToDouble(Double::parseDouble)
.average()
.getAsDouble();
} catch (IOException e) {
e.printStackTrace();
}
我正在尝试对包含 1000 万个数字的文件进行平均,每行一个数字。我创建了一个名为 getAverage() 的方法,returns 是一个双精度值。这是代码:
public double promedioDouble() throws IOException
{
double adder = 0;
int counter = 0;
try{
file = new FileReader(filePath);
reader = new BufferedReader(file);
while(reader.readLine()!=null)
{
adder+=Double.parseDouble(reader.readLine());
counter++;
}
}
catch (IOException e)
{
System.out.println("cant read");
}
finally {
if (file != null) file.close();
}
return adder/counter;
}
我打印了计数器,它显示了 5.000.000,我不知道为什么 reader 无法读取文件中包含的 1000 万数字,它只读取了一半。我需要这方面的帮助。
您调用了 readLine
两次 - 并忽略了在 while
条件下返回的行。
试试看:
String line;
while( (line = reader.readLine()) !=null)
{
adder+=Double.parseDouble(line);
counter++;
}
您也可以使用 Streams 执行此操作(并尝试使用资源 - 避免需要 finally
):
try (Stream<String> stream = Files.lines(Paths.get(fileName)))
{
stream.forEach(s -> {adder+=Double.parseDouble(s); counter++;});
} catch (IOException e) {
e.printStackTrace();
}
我的回答离你的问题有点远。如果您使用的是 Java 8,您可以通过以下方式快速执行此操作:
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
return stream.mapToDouble(Double::parseDouble)
.average()
.getAsDouble();
} catch (IOException e) {
e.printStackTrace();
}