gpt4 book ai didi

java - 从文件中读取并将第一个整数存储为字符串,其余的存储为整数

转载 作者:行者123 更新时间:2023-12-02 10:28:24 26 4
gpt4 key购买 nike

我正在尝试读取文件并存储各个整数,但将文件中的第一个整数放入字符串中。我已经能够读取该文件,但我很难分别存储整数。我想在程序中使用它们。

该文件每行包含三个整数,以空格分隔。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class arrayListStuffs2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the file name: e.g \'test.txt\'");
String fileName = sc.nextLine();
try {
sc = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}

List<String> listS = new ArrayList<>();
List<Integer> listI = new ArrayList<>();

while (sc.hasNextLine()) {
listI.add(sc.nextInt());
}
System.out.println(listI);
}
}

最佳答案

您可以使用以下方法。迭代行,分割它,将第一个作为字符串,另外两个作为整数(假设您的数据为

1 2 3
4 5 6
7 8 9

):

List<String> listS = new ArrayList();
List<Integer> listI = new ArrayList();
// try with resource automatically close resources
try (BufferedReader reader = Files.newBufferedReader(Paths.get("res.txt")))
{
reader.lines().forEach(line -> {
String[] ints = line.split(" ");
listS.add(String.valueOf(ints[0]));
listI.add(Integer.parseInt(ints[1]));
listI.add(Integer.parseInt(ints[2]));
});

} catch (IOException e) {
e.printStackTrace();
}

输出是:

enter image description here

关于java - 从文件中读取并将第一个整数存储为字符串,其余的存储为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53760205/

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