我应该在java中使用什么样的循环?

时间:2012-05-07 00:34:56

标签: java for-loop while-loop

我的布尔表达式在循环中间变为false。我应该使用什么样的循环? 我一直在阅读循环教程,每个人都提到while循环不能这样做。我尝试过组合for循环和if语句,但这也不起作用。对不起这个简单的问题。

    }
     for(int k = 0;k < collb.length; k++){
        //what was used after first calculation
           grosssum += col4[k]*mix[k];
             one=sum1 - grosssum;


    }
   for(int n = 0;n < collb.length; n++)
    if(one < -need[n] && col4[n] >0){
   col5[n]=col4[n]-inc[n] + arrayspecificpounds[n];
    net += col5[n]*mix[n];
    sum = sum1-net;
 }   //net is the sum of what was used * mix
     //sum1 is what we started with
   else{
     if(one > need[n] && col4[n] >0){
    col5[n]=col4[n]-inc[n] + arrayspecificpounds[n];
    net += col5[n]*mix[n];
    sum = sum1-net;

    }
    else col5[n] = col4[n] +  arrayspecificpounds[n];
    sum = sum1 - net;
   }
   for(int p = 0;p< collb.length; p++){
       if(sum < -need[p] && col5[p] >0){
           col6[p]=col5[p]-inc[p] + arrayspecificpounds[p];
       net2 += col6[p]*mix[p];
       sum2 = sum1 - net2;
       }
     else{
           if(sum > need[p] && col5[p] >0){
               col6[p]=col5[p]+inc[p] + arrayspecificpounds[p];
      net2 += col6[p]*mix[p];
    sum2 = sum1 - net2;
           }
    else col6[p] = col5[p] + arrayspecificpounds[p];
    net2 += col6[p]*mix[p];
    sum2 = sum1 - net2;
   }
    }


        for(int q =0;q< collb.length; q++){
           if(sum2 < -need[q] && col6[q] >0){
               colr[q]=col6[q] - inc[q] +arrayspecificpounds[q];
           }
             else{
               if(sum2 > need[q] && col6[q]>0){
                   colr[q]=col6[q] +inc[q] + arrayspecificpounds[q];
               }
       else colr[q] = col6[q] + arrayspecificpounds[q];
           }    

在此示例中,sum2的值随着数组col6的增加而变化,但在数组的中间,不等式会发生变化。一旦sum2改变,我将如何实现一个中断停止?

2 个答案:

答案 0 :(得分:3)

当条件为假时,您可以使用“break”退出任何循环

答案 1 :(得分:3)

这是一个简单的示例,说明当您监视的布尔值将其值从false更改为true时,如何停止while循环:

boolean done = false;
int count = 0;

// while not done, continue looping
while(!done) {
    // do stuff
    count++;
    if(count > 7) {
        done = true;
    }
}

同样的技术实际上也可以在for循环中使用:

boolean done = false;
for(int i = 0; i < 1000 && !done; i++) {
    // do stuff

    if(i > 7) {
        done = true;
    }
}

这有点非正统,但它演示了for循环中的第二个参数如何用于监视可能与int i值的实际值相关或不相关的布尔条件。

相关问题