vendredi 26 mars 2021

Not sure how NOT operator is used in this if-statement?

I can't figure out how the last if-statement executes using !foundWeight. If a user enters a weight that is greater than all the values in letterWeights, foundWeight remains equal to false. If the input is within range, foundWeight is set to true. How, then, does the NOT operator cause the last if-statement to execute when the user input is greater than all the values in letterWeights?

    double[] letterWeights = {1.0, 2.0, 3.0, 3.5, 4.0, 5.0, 6.0,
                              7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0};
    int[] postageCosts = {49, 70, 91, 112, 161, 182, 203,
                          224, 245, 266, 287, 308, 329, 350};
    boolean foundWeight;
    foundWeight = false;
    double userLetterWeight;
    int i;

    for (i = 0; (i < letterWeights.length) && (!foundWeight); ++i) {
       if (userLetterWeight <= letterWeights[i]) {
          foundWeight = true;
          System.out.print("Postage for USPS first class mail is ");
          System.out.print(postageCosts[i]);
          System.out.println(" cents");
       }
    }
 
  **if (!foundWeight)** {
       System.out.println("Letter is too heavy for USPS " +
                          "first class mail.");
    }

Aucun commentaire:

Enregistrer un commentaire