gpt4 book ai didi

java - java中使用分隔符填充数组

转载 作者:行者123 更新时间:2023-12-01 13:15:43 25 4
gpt4 key购买 nike

我有一个用制表符分隔的文本文档。每行都有相同类型的重复信息。当我使用 hasNextLine() 和计数器来计算行数时,它只计算一部分行。我仍然可以创建与我得到的计数器大小相同的数组。当我使用 for 循环填充数组时,结果是意外的。

这是我所做的总结。

    import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args) {
try {
Scanner input = new Scanner(new File("input.txt"));
int lines = 0;
input.nextLine(); //for the header of the table
while(input.hasNextLine()) {
lines++;
input.nextLine();
}
System.out.println(lines);//here I don't get the total amount
String[] colors = new String[lines];
int[] number = new int[lines];
fillArray(colors, number);
System.out.println(colors[i] + i);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void fillArray(String[] color, int[] numbers) {
try {
Scanner input = new Scanner(new File("input.txt"));
input.nextLine(); //for table header
input.useDelimiter("\\t");
for(int i = 0; i < color.length; i++) {
color[i] = input.next();
input.next(); //info i'm not using
numbers[i] = input.nextInt();
input.nextLine(); //consumes '\n'
}
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

它可以编译,但我的结果如下所示:

空\n黄色0\n空1\n空2\n空3\n等等

它还显示正确的颜色和数字;但仅限一行。

如有任何帮助,我们将不胜感激。我没有太多使用 useDelimiter 但据我了解,它会使 '\t' 分隔标记而不是空格和 '\n'

最佳答案

别担心,使用它:

final List<String> lines = Files.readAllLines(Paths.get("input.txt"),
StandardCharsets.UTF_8);

读取的行数就像lines.size()一样简单,您只需遍历列表即可处理您的行。

关于java - java中使用分隔符填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22493668/

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