gpt4 book ai didi

java - 如何用数组中的信息填充数组列表 (java)

转载 作者:行者123 更新时间:2023-11-29 03:34:16 25 4
gpt4 key购买 nike

我正在尝试创建一个从 txt 文件中读取的程序(这是文件“5,5,5,0”中唯一的内容)。然后我想获取该信息,将其放入一个数组中,然后使用该数组填充一个数组列表。然后使用该数组列表将信息写入文件。

这是我目前在我的类文件中的内容:

    import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;

public void setMoney() throws IOException {

File moneyFile = new File ("Money.txt");
Scanner moneyScan = new Scanner(moneyFile);

String [] tokens = moneyFile.split(",");
ArrayList<Integer> money = new ArrayList<Integer>(Arrays.asList(tokens));

for(int i=0;i<tokens.length;i++){
money.append(tokens[i]);
}

String s = Integer.toString(tokens[i]);

FileOutputStream fos = new FileOutputStream("Money.txt");
fos.write(money);
fos.close();
}

Money.append 给我这个错误:

error: cannot find symbol
money.append(tokens[i]);
^

符号:方法追加(字符串) location:ArrayList类型的变量money

moneyFile.split 给我这个错误:

error: cannot find symbol
String [] tokens = moneyFile.split(",");
^
symbol: method split(String)
location: variable moneyFile of type File

最佳答案

您必须使用 FileInputStream 而不是 File。此外,使用您创建的 Scanner 对象来获取 int 值:

FileInputStream moneyFile = new FileInputStream("path/money.txt");
Scanner moneyScan = new Scanner(moneyFile);
moneyScan.useDelimiter(",");
ArrayList<Integer> money = new ArrayList<Integer>();
while(moneyScan.hasNextInt())
money.add(moneyScan.nextInt());

关于java - 如何用数组中的信息填充数组列表 (java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16378451/

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