Monday, 11 July 2011

Java: Fundamentals Cont'd

The last thing we have within the iteration statements thus far is the do statement, also known as a do-while loop. This kind of statement begins with "do", and when the body is completed, the "while" is written to give a condition. This forces the body to be completed at least 1 time, since the condition is checked only after each iteration.

do {
piece.forward();
} while ( piece.canMoveForward() );



Be careful to always have something within the body change something within the condition, though. If the condition does not change, and it's evaluated as true, the loop will never cease running, and the program will not terminate on its own. This will take up resources on your computer at best, at worst your program will fail to ever complete its task.



Now, say for instance we had a puzzle that could be solved by taking a left turn whenever possible, otherwise moving straight ahead. Now, we don't have the quite-so-simple program as before, which was to just keep moving forward. We need to make a selection. To do so, there is such a thing as an if-else statement.


if ( piece.canMoveLeft() ) {
piece.moveLeft();
}
else {
piece.moveForward();
}


The else just means if no previous condition is met, take this as the default action.

We would then put this inside a while loop with the destination being reached as the condition. But what if the piece has to move right if there is no left, and only move forward if no other option is available? Now there are 3 options, so we have an else-if portion to our code.


if ( piece.canMoveLeft() ) {
piece.moveLeft();
}
else if ( piece.canMoveRight() ) {
piece.moveRight();
}
else {
piece.moveForward();
}


Order does matter, so in the above case, the program will first look for a left turn before trying a right, there is then no danger of a right turn being taken if a left one is available.


That's it for today, see all 0 of you next time.

No comments:

Post a Comment