简体   繁体   中英

Is there any way to break and restart for loop if a condition is true?

I want the last loop to stop and restart at the same time if sum is superior to Tamis.PoidsInitial? I mean delete all entered data and restart only the loop and not all code

public static void main(String[] args) {
    double sum = 0;
    DecimalFormat df = new DecimalFormat("0.###");
    Scanner input = new Scanner(System.in);
    Tamis[] listeDesTamis = new Tamis[16];
    System.out.println("Entrer SVP votre poids initial");
    Tamis.setPoidsInitial(input.nextDouble());
    System.out.println("Entrer SVP le tamis avec la taille la plus grande en mm");
    double maille = input.nextDouble();
    for (int i = 0; i < listeDesTamis.length; i++) {
        listeDesTamis[i] = new Tamis(maille);
        maille /= 1.2589;
    }
    for (Tamis e : listeDesTamis) {
        System.out.println("Entrer le refus pour le tamis "
                df.format(e.getTaille()) + " mm en grammes");
        e.setRefus(input.nextDouble());
        sum += e.getRefus();
    }
}

I think you're trying to do something like:

do {
    for (Tamis e : listeDesTamis) {
        System.out.println("Entrer le refus pour le tamis "
                df.format(e.getTaille()) + " mm en grammes");
        e.setRefus(input.nextDouble());
        sum += e.getRefus();
        if (sum > Tamis.getPoidsInitial()) {
            System.out.println("Too much!! Start again.")
            break;
        }
    }
} while (sum > Tamis.getPoidsInitial());

 System.out.println("Phew. We have sufficient.")

I have duplicated a small expression there in order to keep it uncomplicated and give a nice postcondion.

I would tend to avoid boolean flags and continue where practical.

You could do it in one loop using an Iterator that you reassign or reset ( ListIterator ) if you exceed the limit, but that's a bit of a mess too.

(I hope Tamis isn't something rude.")

Put the loop you want to restart inside another loop:

outer: do {
  for (...) {
    if (whatever condition) continue outer;
  }
} while (false);

If the for loop completes without the condition being true, the outer loop doesn't execute again.

Logic along the lines of the below should help get you going in the right direction;

while(booleanVariable == true){

    //do some logic here

    if(someConditionIsMet){
       booleanVariable == false;
       break;
    }

}

将 for 循环中的迭代器(在您的示例中 i)设置为 0,然后 for 循环将重新开始

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM