我正在尝试将文件读取到数组列表中。这个问题已经解决了,我将文件的一行放入数组列表中的一个 block 中。但是,在这个过程中,如果要插入的行包含某些内容,我想获取 block 的索引。这是我到目前为止所做的。我被困住了。
public class practice3 {
public static void main(String[] args) throws Exception {
Scanner data = new Scanner(new FileReader("StudData1.txt"));
ArrayList<String> ArrayData = new ArrayList<String>();
int i = 0;
while (data.hasNextLine()) {
ArrayData.add(i, data.nextLine());
if (data.nextLine().contains("ID: ")) {
System.out.print(ArrayData.indexOf(ArrayData.contains("ID: ")));
}
i = i + 1;
}
// System.out.print(ArrayData.get(2));
// System.out.print(ArrayData.size());
}
}
示例:
************************
Student N. 1
ID: 4450
Surname: Wol
Name: Verine
************************
--------------------------------
Subject N. 1 : a. Boat Mantenance
--------------------------------
Homework 1: 89
Homework 2: 56
Homework 3: 65
Homework 4: 3
Exam 1: 35
Exam 2: 45
Exam 3: 89
Exam 4: 99
最佳答案
请试试这个:
while(data.hasNextLine())
{
//if you call nextLine() two times you will get two different items
String data = data.nextLine();
ArrayData.add(i, data);
if (data.contains("ID: "))
{
System.out.print(ArrayData.indexOf(data));
//check the index of data, but that should be equal to i. no idea what you want to do here?
}
i++;
}
关于java - 如果 ArrayList 中的字符串包含 "",则获取索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21728464/