Administrative Matters

Slides:



Advertisements
Similar presentations
1 karel_IF_part1 Conditional Statements Flavor 1: if ( ) { } For now: these are method invokations (see next slide)
Advertisements

Karel – Making More Complex Decisions IF / THEN / ELSE IF THEN BEGIN Instructions END ELSE BEGIN Instructions END Do these when test = False Do these when.
1 Note: Original slides provided by and modified for Mr. Smith’s AP Computer Science A classwww.apComputerScience.com.
Nested If Statements While Loops
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Karel The Robot Nested If Statements While Loops Copyright © 2008 by Helene G. Kershner.
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
Conditionals How do we solve tasks in which every particular of a task is not specifically known? – A robot needs the ability to survey its immediate environment.
Robot? What’s a Robot? Introducing Karel-the-Robot.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
What is RobotC?!?! Team 2425 Hydra. Overview What is RobotC What is RobotC used for What you need to program a robot How a robot program works Framework.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
An Introduction to Textual Programming
Chapter 5 Conditionally Executing Instructions
1 karel_part5_loops Iteration (Loops) Loops repeat a set of instructions Two types of loops: –Definite loops ( for ) perform instructions explicit (known)
Karel J Robot An introduction to BlueJ and Object- Oriented Programming.
1 Classes begin with capital letters (i.e. UrRobot). Methods, objects, and variable names begin with lower case (camelCase) Use indentation to line up.
1 Note: Original slides provided by and modified for Mr. Smith’s AP Computer Science A classwww.apComputerScience.com.
Programming Errors Lexical errors – occur whenever Karel reads a word that is not in his vocabulary. Example in English: We are asking directions and instead.
Testing and Debugging Version 1.0. All kinds of things can go wrong when you are developing a program. The compiler discovers syntax errors in your code.
Thanks to Dr. Kris Schindler for this (and all Karel the Robot slides)
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
Karel J. Robot Tool for learning OOP (Lecture covers Ch. 1 and 2)
1 Karel – Chapter 6 Instructions That Repeat Note: Original slides provided by and modified for Mr. Smith’s AP Computer Science.
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
1 Karel – Chapter 5 Conditionally Executing Instructions Note: Original slides provided by and modified for Mr. Smith’s AP Computer.
15-100: Introduction to Programming w/ Java * Ananda Gunawardena -- Lecture – School of Computer Science – Phone : (x81559) – Office: Wean Hall.
1 Note: Original slides provided by and modified for Mr. Smith’s AP Computer Science A classwww.apComputerScience.com.
Programming in Karel Eric Roberts CS 106A January 6, 2016.
Ch. 2 1 Karel – Primitive Instructions Basic tools with which all problems are solved (analogies: carpentry, geometry) –move() –turnLeft() –putBeeper()
Karel J. Robot Chapter 6 Instructions That Repeat.
Mile-long hurdle race Suppose that we want to program Karel to run a one-mile long hurdle race, where vertical wall sections represent hurdles. The hurdles.
Karel the Robot – Review Primitive Commands move pickbeeper putbeeper turnleft turnoff Karel’s program statements are separated by a semicolon (;) Copyright.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
1 Karel – Chapter 5 Conditionally Executing Instructions Note: Original slides provided by and modified for Mr. Smith’s AP Computer.
PYTHON WHILE LOOPS. What you know While something is true, repeat your action(s) Example: While you are not facing a wall, walk forward While you are.
1 Chapter 5 Karel J Robot 2 Chapter 5 Chapter 5 Conditional Statements Flavor 1: if ( ) { } For now: these are method invocations (see next slide)
Karel J. Robot Chapter 6 Instructions That Repeat.
Chapter 5: Loops Tarik Booker CS 201 California State University, Los Angeles.
CS 106A, Lecture 3 Problem-solving with Karel
Karel – Primitive Instructions
Lecture 2 D&D Chapter 2 & Intro to Eclipse IDE Date.
Whatcha doin'? Aims: To start using Python. To understand loops.
Mile-long hurdle race Suppose that we want to program Karel to run a one-mile long hurdle race, where vertical wall sections represent hurdles. The hurdles.
In the beginning… software
Eric Roberts and Jerry Cain
Copyright © 2008 by Helene G. Kershner
EGR 2261 Unit 4 Control Structures I: Selection
Warm-up Program Use the same method as your first fortune cookie project and write a program that reads in a string from the user and, at random, will.
Chapter 5: Control Structures II
Loop Structures.
Loops We have already seen instances where a robot needs to repeat instructions to perform a task turnRight(); moveMile(); Harvesting beepers in a field.
Copyright © 2008 by Helene G. Kershner
Karel – Primitive Instructions
Karel J Robot.
CS 106A, Lecture 2 Programming with Karel
Computer Programming Methodology Introduction to Java
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Karel the Robot – Making Decisions
slides courtesy of Eric Roberts
Module 4 Loops.
Python programming exercise
Nested If Statements While Loops
IPC144 Introduction to Programming Using C Week 4 – Lesson 1
Just Enough Java 17-May-19.
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Loops CGS3416 Spring 2019 Lecture 7.
Karel – Primitive Instructions
Presentation transcript:

Administrative Matters No more tirgulim in the computer labs. Use lab support & reception hours to get help. Follow course website, forums, and emails carefully for notices. www.cs.huji.ac.il/~introcsp IntroCSP is meant for students with no previous experience. Only students who got permission may be registered.

Administrative Matters You can find these slides on the website We try to post them early so you can print them (careful not to run out of printing quota). Ex1 is now released. Due next Wednesday. Solve exercises on your own! No copying, no looking at other’s code, no sharing written material. If you consult with someone, write it in your README file.

Hello World Program

Elements of the Program /* * Written by the IntroCSP staff. * This is a short program that prints Hello World. */ public class Hello { public static void main(String[] args){ //Will print out Hello World: System.out.println("Hello World"); } comment Class declaration Main method For now we code here. comment Statement

Compilation and Execution Notice: The file name must be the same as the class name

What if we write it wrong? Compilation Errors A common mistake: writing system instead of System.

What if we write it wrong? Compilation Errors Another common mistake: Forgetting the ;

Variables (Quick Reminder) Different types of variables int Integers: …,-2,1,0,1,2,… boolean true/false: double Real Numbers: 0.1, -0.7,100.0,… char A single character: ‘a’, ‘%’, ‘A’, ’b’ String A sequence of characters: “hello”,”this is a string\n”,”a”

Variables (Reminder) Declaration: Assignment: Both together: int numberOfPeople; Assignment: numberOfPeople=5; Both together: int numberOfPeople=5; Now we can use the variable within expressions: System.out.println(numberOfPeople*2+3); numberOfPeople = numberOfPeople+5;

Naming Conventions The language gives a lot of freedom in choosing variable names. However, for better readability: Use informative names Loop variables can have short names i,j etc. Start variables with a lowercase letter, every added word starts capitalized. Eg: numberOfElements, height, tableWidth

Naming Conventions Start class names with a capital letter. Eg: HelloWorld, LinkedList, Component Stick to this style when you write code! Diverging will cost points on exercises!

Karel’s (Robot) World A simple environment that we built for you. Karel will accompany us in the following couple of weeks Ex1 uses Karel’s world. Karel lives in a 2 dimensional grid world. I.e., each place is identified by a pair (i,j), i,j are integer numbers.

Karel’s (Robot) World N Robot (facing East) wall beeper W E 8 S t r e 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 10 11 12 13 Origin Avenues

Karel’s Capabilities Can move forward Can turn in place Can pick up and put down beepers into his bag Can look at the world and see nearby walls, beepers, etc.

Karel’s Tasks We will try to accomplish different tasks with Karel. For example: Pick up all the beepers in the world. The world we start in may be different every time. We’ll need to give Karel a “flexible” program. Handle different cases that might arise.

A Simple Program with Karel import intro.csp.ex1.BeepersAndWalls; import intro.proceduralKarel.*; public class KarelDemo { public static void main(String[] args){ ProceduralKarel.chooseWorld(BeepersAndWalls.ID, -1); ProceduralKarel.setMoveDelayMilli(1000); //... Here we should tell Karel to do more stuff... ProceduralKarel.turnOff(); } Allows us to use Karel and the BeepersAndWalls World Choose the World to use Animation delay Shuts down Karel and closes the animation window

Karel’s Commands All of Karel’s commands can be found in the documentation of the course library. On the course website go to “useful links” and there see a link to the documentation. All commands start with the prefix ProceduralKarel. They also end with Brackets: (); For example: ProceduralKarel.move();

Karel’s Commands - Statements chooseWorld(World.ID, seed); setMoveDelayMilli(delay); turnOff(); move(); turnLeft(); turnRight(); pickBeeper(); putBeeper(); Selects and loads the world. Sets the animation delay Turns off the robot. You must remember to do this! Move one step forward Turn 90 degrees Pick up one beeper Put down one beeper

Example of a Simple Program import intro.csp.ex1.BeepersAndWalls; import intro.proceduralKarel.*; public class KarelProgram { public static void main(String[] args){ ProceduralKarel.chooseWorld(BeepersAndWalls.ID, -1); ProceduralKarel.setMoveDelayMilli(1000); //here we do some actions with Karel: ProceduralKarel.move(); ProceduralKarel.pickBeeper(); ProceduralKarel.turnLeft(); ProceduralKarel.putBeeper(); ProceduralKarel.turnOff(); } programs need to be more documented than this. Especially in exercises! (We have no room on slides)

Error Shutdown Some of the statements may cause errors if you use them in the wrong situation: putBeeper() when Karel has no beepers pickBeeper() if no beepers at current location move() when facing a wall This causes the program to stop – an error shutdown. Must make sure it never ever happens!

Unsuccessful move and Error Shutoff 1 2 3 4 5 Before move S t r e s Avenues 1 2 3 4 5 After move: Error Shutoff S t r e s

More of Karel’s Commands We can avoid errors by having Karel look at the world around him. The following commands tell us about the world. They have a boolean type (true/false). frontIsClear() leftIsClear() rightIsClear() anyBeepersInBag() anyBeepersInCorner() Checks if there is a wall next to Karel. Check if Karel has beepers Check if there are beepers at the current location.

Example of Safer Use We want to walk only if the way is clear. if(ProceduralKarel.frontIsClear()){ ProceduralKarel.move(); } else{ //we may want to do something here Notice how we use one of Karel’s commands for our condition. Do we always have to check before acting? Not if we know we are safe.

The Rest of the Commands facingEast() facingNorth() facingSouth() facingWest() getBagBeeperNumber() getCornerBeeperNumber() getX() getY() getMoveDelayMilli(); Checks if Karel is facing in a given direction. (boolean type) Tells the number of beepers in the bag and in the corner. (int type) Gets the coordinates Karel is in. (int type) Gets the currently set animation delay. (int)

The Complete Karel Cheat-Sheet chooseWorld(World.ID, seed) setMoveDelayMilli(delay) getMoveDelayMilli() turnOff() move() turnLeft() turnRight() pickBeeper() putBeeper() facingEast() facingNorth() facingSouth() facingWest() frontIsClear() leftIsClear() rightIsClear() anyBeepersInBag() anyBeepersInCorner() getBagBeeperNumber() getCornerBeeperNumber() getX() getY() Don’t forget the prefix: ProceduralKarel.

A Simple Task – Walking Until Karel Faces a Wall A really bad way to do this: if(ProceduralKarel.frontIsClear()){ ProceduralKarel.move(); } …

While loops (Reminder) while( condition ){ Statements } more of the program The condition is checked If it is true: the statements are executed. Return to step 1. If it is false, proceed with the program

More on while Loops The command break; exists the current loop. The command continue; skips the rest of the current iteration and goes back to the beginning. An infinite loop: while(true){…} If your program is in an infinite loop, you can kill it by pressing Ctrl-c.

Walk Till Facing a Wall TwoPacksOfBeepers is another world used in Ex1 import intro.csp.ex1.TwoPacksOfBeepers; import intro.proceduralKarel.*; public class KarelDemo { public static void main(String[] args){ ProceduralKarel.chooseWorld(TwoPacksOfBeepers.ID,-1); ProceduralKarel.setMoveDelayMilli(1000); //walk to the wall ahead: while(ProceduralKarel.frontIsClear()){ ProceduralKarel.move(); } ProceduralKarel.turnOff(); Notice The indentation of the while command

Let’s Pick up Beepers Along the Way Again, notice The indentation. //walk to the wall ahead: while(ProceduralKarel.frontIsClear()){ ProceduralKarel.move(); //if there are beepers, pick one up. if(ProceduralKarel.anyBeepersInCorner()){ ProceduralKarel.pickBeeper(); } What happens to beepers that are in the origin? What if we want to pick up all the beepers in each corner?

Walk to the Wall and Pick Up All Beepers Is there another way to get this task done? //walk to the next wall: while(ProceduralKarel.frontIsClear()){ ProceduralKarel.move(); //pick up and count beepers in this square: int beeperCount = 0; //this will count the beepers while(ProceduralKarel.anyBeepersInCorner()){ ProceduralKarel.pickBeeper(); beeperCount++; } System.out.println("Found " + beeperCount + “ beepers in this corner"); Use informative variable names This println() was too long so we broke it to several lines. Do the same with long lines: break and indent.

For loops (Reminder) for( initialization ; condition ; update){ Statements } Do the initialization Check the condition. If it is true: Execute the statements Execute the update Repeat step 2 Otherwise go on with the program

A Program With a Bug while(ProceduralKarel.frontIsClear()){ ProceduralKarel.move(); //pick up and count all beepers in this square: int counter; //will count the beepers for(counter = 0; counter< ProceduralKarel.getCornerBeeperNumber(); counter++){ ProceduralKarel.pickBeeper(); } System.out.println("Found " + counter + "beepers in this corner"); The program compiles. Can you spot the bug?

A Program With a Bug while(ProceduralKarel.frontIsClear()){ ProceduralKarel.move(); //pick up and count beepers in this square: int counter; for(counter = 0; counter< ProceduralKarel.getCornerBeeperNumber(); counter++){ ProceduralKarel.pickBeeper(); } System.out.println("Found " + counter + "beepers in this corner"); The code would have worked if getCornerBeeperNumber() was computed only at the begining, but it changes when we pick up beepers within the for loop!

Tip: Need to understand a complex loop? Simulate it manually! Another version while(ProceduralKarel.frontIsClear()){ ProceduralKarel.move(); //pick up all beepers in this square: int numBeepers = ProceduralKarel.getCornerBeeperNumber(); for(int i=0; i<numBeepers ; i++){ ProceduralKarel.pickBeeper(); } Tip: Need to understand a complex loop? Simulate it manually!

Tips For Easy Coding and Debugging Compile and Execute often. Don’t let errors accumulate. Write code the right way from the start Don’t go back and change variable names to meaningful names. Use them from the beginning. Don’t go back and indent – do it right the first time.

Tips For Easy Coding and Debugging Open and Close brackets immediately. Use Brackets even for a single expression inside if,for,while Debug using println() inside the code Learn the value of hidden variables, How many times loops are executed, Etc. (Don’t forget to remove the prints later)

Tips For Easy Coding and Debugging Write indented code. It helps! You see where blocks start and end more clearly. Tip: If the Automated indentation of emacs seems wrong, it probably indicates you did something wrong like forget some ‘;’ or ‘}’ Test, test, and test some more.

Allowing the User to Control Karel Let’s allow the user to input orders for Karel. We will use the following commands: 1 to go forward to the nearest wall 2 to turn right 3 to turn left 4 to exit the program

import intro.csp.ex1.TwoPacksOfBeepers; import intro.proceduralKarel.*; import intro.utils.SimpleInput; public class KarelControl{ public static void main(String[] args){ ProceduralKarel.chooseWorld(TwoPacksOfBeepers.ID, -1); ProceduralKarel.setMoveDelayMilli(1000); System.out.println("To control Karel:\n" + "1: Walk to wall\n" + "2: Turn right\n" + "3: Turn left\n" + "4: Exit the program"); boolean notDone = true; //a variable while(notDone){ ... } ProceduralKarel.turnOff(); This import allows us to use SimpleInput Really bad documentation Do the work in here Again, this should be better documented.

while(notDone){ System.out.println("Enter your command:"); int action = SimpleInput.in.readlnInt(); switch(action){ case 1: while(ProceduralKarel.frontIsClear()) ProceduralKarel.move(); break; case 2: ProceduralKarel.turnRight(); case 3: ProceduralKarel.turnLeft(); case 4: notDone = false; default: System.out.println("Huh?"); } Can this program crash? What happens if we forget one of the break; commands?

Walk to the Wall, dance the “Holla” every corner coming back, minimizing number of front is clear() operations int numOfSteps=0; // walk to the wall ahead while(ProceduralKarel.frontIsClear()){ ProceduralKarel.move(); numOfSteps++; } // Turn Back ProceduralKarel.turnRight(); do{ for(int j=1; j<=4; j++){ // turn in a circle numOfSteps--; }while(numOfSteps>0); ProceduralKarel.turnOff(); import and class declaration missing… What if numOfSteps = 0 when we enter the do while statement? When does it happen?

Now dance the Holla all around the world… do{ //dance in a straight line while(ProceduralKarel.frontIsClear()){ ProceduralKarel.move(); //twirl around for(int i=0; i<4; i++){ ProceduralKarel.turnRight(); } //turn and be ready for the next straight line }while(!ProceduralKarel.facingNorth()); Can also write (int i=1; i<=4; i++) and so on… When does the do-while loop stop?