gpt4 book ai didi

java - 使用 FileReader,如何读取 # 列表的下一行,然后将其乘以另一个值?

转载 作者:行者123 更新时间:2023-12-01 12:46:22 24 4
gpt4 key购买 nike

假设我有一个名为 AnnualRateOfReturn.txt 的文件,其中每行都有一个数字列表。我们将该变量称为 X。从文件中读取的数字将是百分比。

在一个循环中,我想采用一个变量(假设是 Y),然后将其乘以从第一行 AnnualRateOfReturn 读取的 1.X 值。

再次循环后,我希望它采用一个新值,从文件 AnnualRateOfReturn.txt 的下一行读取,然后将 Y 值乘以新的 1.X 变量。

对于每个循环,它应该读取下一行,然后将 Y 变量乘以该值。

示例:

AnnualRateOfReturn.txt

Line1: 0.04
Line2: 0.24

在第一个循环中,Y 值应乘以 1.04在第二次循环中,应读取下一行,并将 Y 值乘以 1.24

我需要使用 FileReader 类来完成此任务。

最佳答案

//create a Scanner to scan through the file that FileReader reads
//note: must deal with FileNotFoundException
//which will be thrown if FileReader(source) cannot find the source file
Scanner scanner = new Scanner(new FileReader("path/to/AnnualRateOfReturn.txt"));
//scanner.hasNext() ensures that the scanner has a token to read
while(scanner.hasNext()){
//create your x value, this will throw an exception if the next token isn't a Double
double x = 1 + scanner.nextDouble();
//do your math
y = y*x;
}

关于java - 使用 FileReader,如何读取 # 列表的下一行,然后将其乘以另一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24665341/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com