gpt4 book ai didi

java - 从文本文件的一行中读取每个整数

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

我是 Java 新手。我如何从文本文件中的一行读取每个整数。我知道 reader 类具有 read 和 readline 函数。但就我而言,我不仅想读取文件中的整数,还想知道该行何时发生变化。因为每行的第一个元素表示一个数组索引,所有相应的元素都是附加到该索引的链表值。

例如,请参见下面的第 4 行。在这种情况下,我不仅想读取每个整数,而且每行的第一个整数将是一个数组索引,因此我将有一个 4 元素数组,每个数组元素对应于一个列表,其中 A[1]-> 4, A [2]-> 1、3、4 等等。

1 4

2 1 3 4

3 2 5

4 2

正确检索整数后,我计划通过填充它们

ArrayList<Integer>[] aList =  (ArrayList<Integer>[]) new ArrayList[numLines];

已编辑:有人在评论中问我到目前为止我的想法以及我到底在哪里陷入困境,所以下面是我的想法(就原始代码和伪代码混合而言)..

 while (lr.readLine() != null) {

while ( // loop through each character)
if ( first charcter)
aList[index] = first character;
else
aList[index]->add(second char.... last char of the line);
}

谢谢

最佳答案

感谢安德鲁·汤普森的扫描仪提示。

这就是我实现它的方法

    Scanner sc =new Scanner(new File("FileName.txt"));

ArrayList<Integer>[] aList = (ArrayList<Integer>[]) new ArrayList[200];
String line;
sc.useDelimiter("\\n");
int vertex = 0;
while (sc.hasNextLine()) {
int edge = 0;
line = sc.nextLine();
Scanner lineSc = new Scanner(line);
lineSc.useDelimiter("\\s");
vertex = lineSc.nextInt() - 1;
aList[vertex] = new ArrayList<Integer>();
int tmp = 0;
System.out.println(vertex);

while (lineSc.hasNextInt()) {
edge = lineSc.nextInt();
aList[vertex].add(edge);
System.out.print(aList[vertex].get(tmp) + " ");
++tmp;
}
System.out.println ();
}

关于java - 从文本文件的一行中读取每个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11371502/

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