Sunday, September 25, 2016

Java Flow Control.

Conditional Flow Control
if (x > 4) y = x;
if (y == 99 || y < 0) {
   z = x;
} else if (y > 50) {
   z = y;
} else {
   z = x + y;
}

//
switch (count) {
    case 0:
    case 1:
        total = count * 0.5;
        break;
    case 2:
        total = count * 0.8;
        break;
    default:
        total = count * 1;
        break; // redundant, to prevent copy paste error when
               // some like to put this in the beginning of switch
}
//
// starting from Java 1.7, 
// you can compare switch variable to String literals in case
//

Loop Control
for (int i=0; i < 3; i++) { // Here ++i or i++ doesn't make a difference
    if (i%2 == 0) {
        System.out.println (i);
    }
}
int k = 0;
for ( ; k < 3 ; ) { // It is okay.
    k++;
}

for ( ; ; ) {
    if (k > 4 ) break;
    k++;
}
start:
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 4; j++) {
        if (j == 2) {
            break start;
        } else { // redundant, to show continue usage
            continue start;
        }
    }
}
//
int i = 0;
// to produce three beeps with a 500 milliseconds interval 
// between two beeps
while (i < 5) { // without semicolon! 
                // Compiler won't error out with it! Be cautious!
    java.awt.Toolkit.getDefaultToolkit().beep();
    try {
        Thread.currentThread().sleep(500);
    } catch (Exception e) {
    }
    i++;
    if (i > 2) break;
    else continue;
}
do {
    System.out.println (i);
    i++;
} while (i < 3); // with semicolon

No comments:

Post a Comment