有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java分支数组如果包含“true”

我有一个for循环,它在数组中循环

for(int i = 0; i<=(clientListpost.length -1); i++){
    if(clientpost[i] == true) {
      if((clientpost[i+1] == true) || (clientpost[i+2] == true) || (clientpost[i+3] == true)) {
        clientString[i] = client[i] + ",";
      } else {
        clientString[i] = client[i];
      }
    } 
  }

我在第二个if-else中检查以下数组之一是否包含true

如果我有大约40个以下阵列,如何压缩第二个if条件

我不能使用indexOf(),因为它将始终在所有索引中搜索

示例:

My clientListpost=>;[false,false,false,false]取决于表单上选择的内容(如果已选择=>;true)

我的clientpost现在为8个数组添加了速率,以使第二个if条件起作用=>if((clientpost[i+1] == true) || (clientpost[i+2] == true).. 我这样做是因为如果我点击最后一个数组,它会给我一个错误,数组(5,6,7..)不存在

My clientString=>;[“”、“”、“”、“”、“”]为空。因为如果clientpost数组为false,则它具有字符串值

我的客户=>;[1015103510401070]为clintString数组提供值

最后,我就这样把它们连成一排:

String clientUrl = "";
  for(int i = 0; i<=(clientListpost.length -1); i++){
    clientUrl += clientString[i].toString();
  }

输出:

如果仅选择了1015=>1015

如果选择1030和1045=>10301045

如果选择了1045和1070=>10451070

提前谢谢


共 (2) 个答案

  1. # 1 楼答案

    看起来您可以创建一个附加方法来确定是否需要向clientString[i]添加逗号

    for(int i = 0; i<=(clientListpost.length -1); i++){
        if(clientpost[i]) {
            clientString[i] = client[i];
    
            if (isClientPostEnabled(clientListpost,clientListpost.length -1, i)) {
                clientString[i] += ",";
            }
        }
    }
    
    public static boolean isClientPostEnabled(List<bool> clientListpost,int index, int startIndex) {
        for (int i = startIndex; i < index - startIndex; i++) {
            if (clientpost[i]) {
                return true;
            }
        }
        return false;
    }
    
  2. # 2 楼答案

    我将在这里做一些假设(请同时参考您问题评论中我的问题):

    • 您确实需要像这样构建阵列
    • 您已确保未抛出ArrayIndexOutOfBoundsException

    与其检查是否添加了任何后续元素,不如向后迭代:

    boolean subsequentElementsSelected = false;
    for(int i = clientListpost.length -1; i >= 0; i ){
      if(clientpost[i]) { //or clientpost[i] == true
        if(subsequentElementsSelected ) { 
          clientString[i] = client[i] + ",";
        } else {
          //only true for the last element to be added/set
          clientString[i] = client[i];
        }
    
        //once we've added an element at the end this will stay true
        subsequentElementsSelected  = true;
      } 
    }
    

    根据您的评论:

    I do reduce them into a single string at the end.

    如果不需要clientString数组,只需将其追加到字符串中,并在需要时添加逗号:

    StringBuilder builder = new StringBuilder();
    for(int i = 0; i <= clientListpost.length -1; i++){
      if(clientpost[i]) { //or clientpost[i] == true
    
        //if there's already something in the String, add a comma first
        if(builder.length() > 0) { 
          builder.append(",");
        } 
    
        //add the element
        builder.append(client[i]);
      } 
    }
    clientUrl += builder.toString(); //assumes there's more in clientUrl, otherwise just assign