![](/img/trans.png)
[英]java arraylist<string> check for the first and last value that fulfills a condition
[英]Iterate through arraylist and assign value for first and last value that fulfills requirement
我有一个方法,该方法传入数据的数组列表和一个printwriter,将我的输出打印到一个csv文件中。 数组列表的名称是记录。
for (String record: records){
String[] recordSplit = record.split(",");
double value = Double.parseDouble(recordSplit[2]);
writer.println(record);
}
当遍历arraylist时,代码应逐行打印到csv文件中。 (字符串记录)但是,我想做的是循环循环,我想检查小于20的value <= 20
并且满足该条件的arraylist中的第一个值将在csv文件中包含另一列输出例如
record += ",Start Value";
然后迭代器达到满足条件的LAST值,它将有一个额外的列,如下所示:
record += ",End Value";
我在上图中说明了这个概念。 这是arraylist,“ id,name,value”,还有更多与value后面的问题无关的属性,因此我将其省略。 无论如何,可以将value = 100视为“禁止值”,因此当循环到达arraylist的末尾之前或再次看到值100的那一刻,该值将被分配为“ End”值。 可以实际完成吗? 我是java的业余爱好者,所以请客气,谢谢!
无论如何,输出应如下所示:
这里是一个简化但可行的示例,您可以从中开始。 该片段使用来自Kevins注释的示例值。
这里简要说明如何确定不同的状态
示例片段
public static void main(String[] args) {
int[][] samples = {
{100, 20, 12, 15, 19},
{45, 5, 100, 4, 12, 100, 6},
{2, 3, 100, 4, 5, 60}
};
outputValues(samples);
}
private static void outputValues(int[][] samples) {
int startIndicator = 100;
int upperBound = 20;
for (int[] sample : samples) {
int startIndicator = 100;
int upperBound = 20;
for (int[] sample : samples) {
System.out.println("---------------");
boolean startIndicatorFound = false;
boolean startValueFound = false;
boolean endValueFound = false;
for (int i = 0; i < sample.length; i++) {
int value = sample[i];
System.out.printf("%d", value);
if (endValueFound) {
// do nothing
} else if (i == (sample.length - 1)
|| startValueFound && sample[i + 1] > upperBound) {
endValueFound = true;
System.out.print(",End Value");
} else if (startIndicatorFound && !startValueFound
&& value <= upperBound) {
startValueFound = true;
System.out.print(",Start Value");
} else if (!startIndicatorFound && value == startIndicator) {
startIndicatorFound = true;
}
System.out.println("");
}
}
}
输出
---------------
100
20,Start Value
12
15
19,End Value
---------------
45
5
100
4,Start Value
12,End Value
100
6
---------------
2
3
100
4,Start Value
5,End Value
60
仍然存在一些当前案例未涵盖的极端情况。
这应该使您开始:
Boolean started = false; // To keep track if we already wrote "Start Value"
for (int i = 0; i < records.length; i++) {
String record = records.get(i);
String[] recordSplit = record.split(",");
double value = Double.parseDouble(recordSplit[2]);
if(value < 20 && ! started) { // Starting here
writer.println(record + ",Start Value");
started = true;
continue; // Go to next record
}
if(i < records.length - 1) { // There is a next value
if(Double.parseDouble(records.get(i + 1).split(",")[2]) < 20) {
// Next value is also smaller than 20, so keep going
writer.println(record);
} else {
writer.println(record + ",End Value");
started = false; // So we can start again later
} else {
writer.println(record);
}
}
(未测试)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.