java如何停止循环并获取计数器

时间:2016-11-19 13:24:35

标签: java loops counter

我只是在这里停留了五个小时,我只想获得信息的价值,它是一个计数器并从零开始但是当给定的条件满足时我只想获得计数器的值。有没有 更好,更简单的方法来获得这个? 我的代码如下:

for(int info = 0; info<currentData.length();info++ ) {
    JSONObject managedata = currentData.getJSONObject(currentData.length() - 1);
    long getcurrenttime = managedata.getLong("dt");

    while (getcurrenttime > currentEpochTime) {
        // i want to get the 'info' value here when the following condition meet.
    }

4 个答案:

答案 0 :(得分:0)

尝试这个

unrelated_text

答案 1 :(得分:0)

你需要在for循环之前创建一个变量来存储循环中的info值,如下所示:

//some method
int storedInfo=0;
for(int info = 0; info<currentData.length();info++ ) {
    JSONObject managedata = currentData.getJSONObject(currentData.length() - 1);
    long getcurrenttime = managedata.getLong("dt");

    if (getcurrenttime > currentEpochTime) {
        // i want to get the 'info' value here when the following condition meet.
        storedInfo=info;
        //you can break further looping as condition met and you have stored info value above
       break;

    }

答案 2 :(得分:0)

你应该在条件满足时休息。我还会引入一个布尔值,所以我知道条件是否至少匹配一次:

int info = 0;
boolean conditionMatch = false;

for(int info = 0; info<currentData.length();info++ ) {
    JSONObject managedata = currentData.getJSONObject(currentData.length() - 1);
    long getcurrenttime = managedata.getLong("dt");

    while (getcurrenttime > currentEpochTime) {
        // i want to get the 'info' value here when the following condition meet.
        conditionMatch = true;
        break;
    }
}
if(conditionMatch){
    System.out.println("Condition matched when counter was:" + info);
else{
    System.out.println("Condition not matched");
}

答案 3 :(得分:0)

尝试以下代码 -

    int info = 0;
    for(; info<currentData.length();info++ ) {
        JSONObject managedata = currentData.getJSONObject(currentData.length() - 1);
        long getcurrenttime = managedata.getLong("dt");

        if (getcurrenttime > currentEpochTime) {
            // i want to get the 'info' value here when the following condition meet.
           break;

        }
   }
   if(info != currentData.length()){
      System.out.println(info);
   }