我仍在掌握 Java。我需要一些帮助来循环数组。
我的数组看起来像这样;
String [] allRecords = ["[BEGIN RECORD]", "[ID]1", "[cName]Agnes", "[Age]12", "[END RECORD]", "[BEGIN RECORD]", "[ID]2", "[cName]Hellen", "[Age]5", "[END RECORD]", "[BEGIN RECORD]", "[ID]3", "[cName]Jack", "[Age]34", "[END RECORD]" ];
<小时/>
//i use the below code to identify the beginning and end of a record in the array
String beginRecord = "[BEGIN RECORD]";
boolean foundBeginRecord = false;
int foundIndex = 0;
for (int i=0; i<allRecords.length; i++) {
if (beginRecord.equals(allRecords[i])) {
foundBeginRecord = true;
foundIndex = i+1; //added one
break;
}
}
String endRecord = "[END RECORD]";
boolean foundEndRecord = false;
int foundEnd = 0;
for (int i=0; i<allRecords.length; i++) {
if (endRecord.equals(allRecords[i])) {
foundEndRecord = true;
foundEnd = i; //one NOT added
break;
}
}
<小时/>
//i then use the below code to slice off part of the array
String [] partAllRecords = Arrays.copyOfRange(allRecords, foundIndex, foundEnd);
//这给了我一个新的子数组,如下所示:“[ID]1”,“[cName]Agnes”,“[Age]12”
上面的代码工作正常。我现在需要的是从 allRecords 数组中读取/切片另一部分,即; "[ID]2", "[cName]Hellen", "[Age]5" 然后切片下一个 block "[ID]3", "[cName]Jack", “[Age]34” 直到 allRecords 数组的末尾。
我该怎么做?
谢谢!
最佳答案
您现有的代码很接近,可以很容易地修改以完成您想要的操作。要记住的关键事情是从您上次停下的地方开始,而不是从 0 处重新开始,而您现在没有这样做。所以您已经(为了说明而大大简化了):
int foundIndex = 0;
for (int i=0; i<allRecords.length; i++)
... find start record
int foundEnd = 0;
for (int i=0; i<allRecords.length; i++) {
... find end record
请注意,每次都从 0 开始。但是,您知道一些事情:
- 起始记录不会在上一条结束记录之前,因此我们可以在上一条记录之后开始搜索。
- 结束记录不会在开始之前,因此我们可以从开始索引处开始搜索。
然后,通过保存上一条记录末尾的位置并从那里开始,您的逻辑现在可以在循环中重复,直到从输入中消耗掉所有有效记录。
考虑到这一点,又过于简单化了:
int foundIndex, foundEnd = -1;
do {
foundIndex = 0;
for (int i=foundEnd + 1; i<allRecords.length; i++)
... find start record
foundEnd = 0;
for (int i=foundIndex + 1; i<allRecords.length; i++) {
... find end record
} while a record was found;
还有其他可能的方法来简化代码(例如,将 ArrayList
与 indexOf()
一起使用,使用简单的状态机等),但上述内容仍然存在非常接近您当前的代码。
关于java - 从一个主数组创建子数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22617500/