Lobstw
Lobstw

Reputation: 499

Extra while loop conditions ... based on a condition

The variable a can be 0, 1 or 2, where the value is the number of extra while loop conditions to have. I can do this using switch and case but I'm wondering if there's a better way of doing it?

switch (a) {
    case 0: while (condition_1) {
        // ...
    } break;
    case 1: while (condition_1 || condition_2) {
        // ...
    } break;
    case 2: while (condition_1 || condition_2 || condition_3) {
        // ...
    } break;
}

The solution to this problem in Python was to use a dictionary and store the appropriate lambda expressions in the appropriate index. However, my conditions are "not final or effectively final" so they cannot be used in a lambda expression in Java.

The aim here isn't to get either a while (true) or a while (false) and be done with it. It's to start off with a while (...something) which evaluates to false THEN inside the loop do something that changes all of the conditions to true one by one. But until all of the conditions are true, keep looping.

Pseudo code (I know it has some flaws, just for demonstration):

a can be 0,1,2

p = 5
q = 7
r = 10
s = 14

if a = 1
while p != q -> p+=1
if a = 2
while p!= q || p!= r -> p+=1

Also, this is a teach me to fish instead of giving me the fish type question.

Upvotes: 3

Views: 335

Answers (2)

Jason Hu
Jason Hu

Reputation: 6333

remind you java switch supports fall through. you will need a helper function to do it, since switch-case in java is statement instead of expression:

private boolean helper(a) {
    boolean b = false;
    switch (a) {
        case 2: b = b || condition_3;
        case 1: b = b || condition_2;
        case 0: b = b || condition_1;
    }
    return b;
}

i can't really think of any case where you can't put a helper function. if that's true, i would like to learn about it. (in fact in python's case, the answer also suggests you to use helper(in lambda form))

Upvotes: 0

Let's say you have a condition list defined.

boolean[] condition = new boolean[n];

a is the number of booleans you wish to check, so just create a new variable

boolean valid = false;


//check all conditions up to a
for (int i = 0; i < a; i++) {
    if (condition[i]) {
        valid = true;
        break;
    }
}

while (valid) {
    //perform action and then run the checking valid code again
}

In this case, you will be checking for a conditions in total, which is what you want.

Upvotes: 1

Related Questions