gpt4 book ai didi

java - 查找从文件读取的字母数字数组中的数字元素并将其写入新文件

转载 作者:行者123 更新时间:2023-11-30 06:54:29 26 4
gpt4 key购买 nike

所以我的目标是读取一个文本文件,该文件是一个包含整数和字符串的数组,然后对一些数字进行一些计算,然后将原始数据与新计算的数据一起放入新的文本文件中。但现在我陷入了困境,我似乎无法从文件中挑选数字并将它们放入 ArrayList 中,除非我把这一切都搞错了。谢谢。

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


public class LAB02 {

public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub

Scanner input = new Scanner(System.in);

Scanner fileStockIn = new Scanner(new FileReader("Lab02Input.txt"));
PrintWriter reportFile = new PrintWriter("Lab02Report.txt");



ArrayList<Double> list = new ArrayList<Double>();

while(fileStockIn.hasNext()) //while loop to stay in loop while there are more records
{//begin while
double price = input.nextDouble();
double shares = input.nextDouble();
double dividend = input.nextDouble();
String ticker = input.next();

Double record = new Double(price, shares, dividend);
list.add(record);


}//end while


fileStockIn.close( );
reportFile.close( );

}

}

我正在读取的文本文件的输入(添加项目符号是为了更容易阅读):

  • 42.87 23.33 2.10 执行
  • 12.00 83.33 0.17 ATVI
  • 28.15 35.00 0.80 微软金融科技
  • 42.98 23.26 0.65 CVS
  • 33.64 29.72 2.20 TXN
  • 55.51 18.01 2.00 NVS
  • 16.00 62.50 0.40 SPLS
  • 19.81 50.47 0.24 CSCO
  • 30.09 33.23 1.76 T
  • 39.29 25.45 0.60 DIS
  • 18.65 53.00 0.29 SNE
  • 50.21 19.21 0.72 AXP
  • 102.69 9.74 1.44 尼库

最佳答案

我不知道您如何尝试使用具有 3 个参数的构造函数实例化 Double 类型。请参阅此处的文档,了解 Double 的工作原理。

https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html

您想要做的是 - 您需要一个自定义类来保存如下三个属性:

 private class Calculation  {
int price;
double shares;
double dividend;

//getters and setters here
//constructor
public Calculation (int price, double shares, double dividend) {
this.price=price;
this.shares = shares;
this.dividend = dividend;
}
}

然后在你的主类中

     List<Calculation> calculations = new ArrayList<Calculation>();
while(fileStockIn.hasNext()) {
//begin while
int price = input.nextInt();
double shares = input.nextDouble();
double dividend = input.nextDouble();
String ticker = input.next();

Calculation calculation = new Calculation(price, shares, dividend);
calculations.add(calculation);
}

希望这有帮助。

关于java - 查找从文件读取的字母数字数组中的数字元素并将其写入新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42104727/

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