在for循环中更改迭代变量

时间:2016-05-31 17:38:13

标签: java arrays

我试图在数组中打印一些元素。我的数组就像,

prmArray={"[]","int","[]","[]","float","[]","[]","[]","string"}

我试图打印的是

int[] float[][] string[][][]

我一直在尝试各种各样的东西,现在它变得混乱了.. 我的代码是,

 String ps=""; 
 int u=0; 
    for(int y=0;y<prmArray.length;y=u)
        {
            String br_string="";

            if(prmArray[y].equals("[]")){
                int f=y+1; 
                br_string+="[]";
                for(int h=f;h<prmArray.length;h++){
                    u=h;
                    if(prmArray[h]=="[]"){
                        br_string+="[]";
                    }
                    else{
                        u=u-1; 
                        break;
                    }
                }
                ps+=prmArray[u+1]+br_string+" ";
                u=u+2;
            } 

            else{
                ps+=prmArray[y]+" ";
                u=u+1;
            }
        }
        System.out.println(ps);

请帮助..

3 个答案:

答案 0 :(得分:0)

您可以使用此功能:

public static String formatArray(String[] prmArray){
    String result = "";
    String tempResult = "";
    for (String entry: prmArray){
        if(entry.equals("[]")){
            tempResult += entry;
        }else{
            tempResult = entry + tempResult;
            //flip tempResult
            result += tempResult + " ";
            tempResult = "";
        }
    }
    return result;
}

答案 1 :(得分:0)

堆栈实现:

import java.util.Stack;

public class Stk {
    public static void main(String...orange)
    {
        String [] prmArray={"[]","int","[]","[]","float","[]","[]","[]","string"};
        Stack<String> stack = new Stack<String>();
        for (String str : prmArray)
        {
            if (str.equals("[]"))
                stack.push(str);
            else
            {
                while(!stack.isEmpty())
                    str+=stack.pop();
                System.out.print(str + " ");
            }
        }
    }
}

输出:

int[] float[][] string[][][] 

答案 2 :(得分:0)

如果我很清楚你想要做什么,你不需要嵌套循环,你可以一次性完成,把你遇到的br_string "[]"放进去至今。 当你找到其他东西时,你会构建最终结果的一部分(ps)并继续;-)

public static void main(String[] args) {
    String[] prmArray={"[]","int","[]","[]","float","[]","[]","[]","string"};

    String ps = "";
    String br_string="";

    for (int i = 0 ; i< prmArray.length ; i++) {

        if(prmArray[i].equals("[]")){
            br_string += prmArray[i];
        } else {
            br_string = prmArray[i] + br_string + " ";
            ps += br_string;
            br_string = "";
        }
    }

    System.out.println(ps);

}