Careeroza
Conditions and Loops
if, else and for
Conditions decide pass or fail. Loops repeat an action, for example checking every product on a search page.
Example
Check that every product price is within the selected filter (500 to 2000):
public class Main {
public static void main(String[] args) {
int[] prices = {799, 1299, 1999, 2499, 650};
int min = 500, max = 2000;
int failures = 0;
for (int i = 0; i < prices.length; i++) {
if (prices[i] >= min && prices[i] <= max) {
System.out.println("Product " + (i + 1) + ": " + prices[i] + " OK");
} else {
System.out.println("Product " + (i + 1) + ": " + prices[i] + " OUTSIDE FILTER");
failures++;
}
}
System.out.println(failures == 0 ? "PASS" : "FAIL (" + failures + " wrong)");
}
}Output
Product 1: 799 OK Product 2: 1299 OK Product 3: 1999 OK Product 4: 2499 OUTSIDE FILTER Product 5: 650 OK FAIL (1 wrong)
while for Retrying
Example
A while loop is handy for "try again up to 3 times":
public class Main {
public static void main(String[] args) {
boolean[] attempts = {false, false, true}; // pretend the 3rd try succeeds
int tries = 0;
boolean ok = false;
while (!ok && tries < 3) {
ok = attempts[tries];
tries++;
System.out.println("Attempt " + tries + ": " + (ok ? "success" : "failed"));
}
System.out.println("Result after " + tries + " tries: " + ok);
}
}Output
Attempt 1: failed Attempt 2: failed Attempt 3: success Result after 3 tries: true