【问题标题】:How to return to beginning of while loop java如何返回到while循环java的开头
【发布时间】:2014-10-18 04:21:42
【问题描述】:

如何跳出 forloop 并返回到 while 循环的开头。当我输入 1211 时,我的函数应该返回 111221,因为有一个 1、一个 2 和两个 1。如果有人有任何想法,我将不胜感激。

public static String occurence(String input) {

    int s = 0;
    String out = "";

    int count = 0;

    while(s < input.length()) {

        int num = getInt(input, s);

        for(int r = s; r < input.length(); r++) {

            if(num == getInt(input, r)) {
                count++;
            } else {
                System.out.println(count);

                out += count;
                out += num;
                s += count;
                count = 0;

                // Jump to start of while loop
            }
        }
    }
    return out;
}

【问题讨论】:

  • 你的 getInt 方法是什么,它返回什么?请提供完整代码。
  • 或者只使用 Break 语句退出循环。

标签: java loops while-loop break


【解决方案1】:

使用break语句

 public static String occurence(String input){

int s = 0;
String out = "";

int count = 0;


while(s<input.length()){


    //System.out.println(s);

    int num = getInt(input, s);

    for(int r = s; r<input.length(); r++){


        if(num == getInt(input, r)){

            count++;


        }else{

            System.out.println(count);

            out+=count;
            out+=num;
            s+=count;
            count = 0;

            break;



        }

    }

}

return out;


}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 2018-08-22
    相关资源
    最近更新 更多