Karel J Robot - Chapter 4: Conditional Instructions     BACK TO KAREL MAIN

 AP Home Karel Unit 1 Unit 2 Unit 3 Unit 4 Unit 5 Unit 6 Unit 7 Progs Tests

 Conditional Instructions Real robots use artificial intelligence (AI) to make decisions. The use of AI enables robots to “think” and do things on their own. It is time to work with such robots using Karel. We begin with a programming structure that permits such decision-making: the if statement. The IF statement if(condition) {    list of statements } Example: How to avoid running into a wall if(frontIsClear()) {    move(); } This code will allow karel to move forward if there is no wall in front of him, but will do nothing if there is a wall in front. The frontIsClear() method comes from a different, yet standard, robot class called, simply, Robot (see its definition and methods below). The Robot Class Boolean Methods –    boolean frontIsClear();    boolean nextToABeeper();    boolean nextToARobot();    boolean facingNorth();    boolean facingSouth();    boolean facingEast();    boolean facingWest();    boolean anyBeepersInBeeperBag(); You may have noticed that none of these methods have the word void in their headings, but rather the word boolean. The term boolean, named after mathematician George S. Boole, refers to a system of logic which only deals with two values, specifically true and false. A boolean method returns a value of true or false based on the current state of the robot and the given condition. So these methods, unlike void ones, communicate back when they are called. Their response determines whether the robot will act or not act on another command or commands. As such, they must be used inside the parentheses of an if statement. The IF-ELSE statement - If a second action should be performed when the condition is false, it is useful to use an if-else statement. See the format below: if(condition) {    list of statements } else {    another list of statements } So if the condition is TRUE, the statements in the if block are enacted; if the condition is FALSE, the statements in the else block are enacted.