【问题标题】:Skipping element in a for loop and reassigning it在 for 循环中跳过元素并重新分配它
【发布时间】:2015-07-30 08:52:15
【问题描述】:

我在 JasperSoft 中填写参数。在我的报告中,我有参数: 参数_1、参数_2、参数_3

int a; 
for (a = 0; a < headers.length; a++) {
        parameters.put("Parameter_" + a, headers[a]);
    }

我以这种方式填充参数并且它有效。现在我想添加一个新参数 Parameter_GroupBy,它由它的索引决定(假设我希望 Parameter_2 成为 Parameter_GroupBy)所以我这样做了:

int a; 
for (a = 0; a < headers.length; a++) {
        if (a == groupBy) {
            parameters.put("Parameter_GroupBy", headers[groupBy]);
            continue; 
        }
        parameters.put("Parameter_" + a, headers[a]);
    }

此代码的问题(假设 groupBy 值为 2)是 Parameter_2 为空,但我希望它具有 Parameter_3 的内容

例如

Parameter_1= name 
Parameter_2= date 
Parameter_3= street

我得到的第二个代码位

Parameter_1 = name 
Parameter_2= 
Parameter_GroupBy= date 
Parameter_3= street

我想按日期分组(Parameter_2)所以我想要

Parameter_1 = name 
Parameter_2= street 
Parameter_GroupBy= date 
Parameter_3=

如何做到这一点?使用 JDK 1.6 和 Windows。

【问题讨论】:

    标签: java loops for-loop foreach


    【解决方案1】:

    在我看来,您只需要为“下一个要放置的参数”保留一个单独的索引:

    int parameterIndex = 1;
    // Note: more idiomatic to declare the iteration variable
    // inside the loop
    for (int headerIndex = 0; headerIndex < headers.length; headerIndex++) {
        String header = headers[headerIndex];
        if (headerIndex == groupBy) {
            parameters.put("Parameter_GroupBy", header);
        } else {
            parameters.put("Parameter_" + parameterIndex, header);
            parameterIndex++;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-07-17
      • 1970-01-01
      • 1970-01-01
      • 2020-04-07
      • 1970-01-01
      • 2012-03-02
      • 1970-01-01
      • 2014-01-08
      • 2022-06-30
      相关资源
      最近更新 更多