2
    String input[] = request.getParameterValues("checkbox");

        for(int i=0;i<input.length;i++) {
            if (i==input.length-1) {
                System.out.print(input[i]+" ");
            } else {
                    System.out.print(input[i]+", ");
            }
        }

结果是我打印到控制台,例如“CustomerId、FirstName、LastName、Phone”。我想将 for 循环的结果保存为字符串变量,所以我可以这样做

     String query = "select "+result above+" from table";

怎么做?

4

3 回答 3

3

您不断追加到 aStringBuilder然后将其转换为String

StringBuilder sb = new StringBuilder();
for(int i=0;i<input.length;i++) {
  if (i==input.length-1) {
     System.out.print(input[i]+" ");
     sb = sb.concat(input[i] + ",");
  } else {
     System.out.print(input[i]+", ");
     sb = sb.concat(input[i] + ",");
  }
}

然后,

String query = "select "+sb.toString()+" from table";
于 2013-09-17T14:20:37.823 回答
2

使用StringBuilder将字符串连接在一起。(技术上可以使用 String 对象,并使用 + 运算符将它们连接在一起,但这有很多缺点......)

    String input[] = request.getParameterValues("checkbox");

    StringBuilder sb = new StringBuilder(); // create empty StringBuilder instance
    for(int i=0;i<input.length;i++) {
        sb.append(input[i]);     //append element
        if (i==input.length-1) {
            sb.append(" ");      //append space
        } else {
            sb.append(", ");     //append comma
        }
    }

    String result = sb.toString();
    Systemout.println(result);

或者您可以使用 StringBuilder 对象构建(参见 Builder 模式)整个查询,每个部分都有方法(addFields(StringBuilder sb), addFromPart(StringBuilder sb), addWhereClause(StringBuilder sb)),瞧,您拥有一个小型数据访问框架的内部......

public abstract class MyQueryBuilder {

    protected abstract void addFields(StringBuilder sb);
    protected abstract void addFromPart(StringBuilder sb);
    protected abstract void addWhereClause(StringBuilder sb);

    public final String getQuery() {
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT ");

        addFields(sb); //this adds the fields to be selected
        sb.append(" FROM ");

        addFromPart(sb); //this adds the tables in the FROM clause

        addWhereClause(sb); //this adds the where clause
        //...etc
        return sb.toString();
    }
}
于 2013-09-17T14:20:20.150 回答
1

您可以使用 StringBuilder 来执行此操作,而不是将值打印出来。

String input[] = request.getParameterValues("checkbox");

    StringBuilder builder = new StringBuilder();

    for(int i=0;i<input.length;i++) {
        if (i==input.length-1) {
            builder.append(input[i]+" ");
        } else {
                builder.append(input[i]+", ");
        }
    }

问候,凯兹

于 2013-09-17T14:24:35.607 回答