Java (SuperKarel)
move(); |
turnLeft(); |
|
turnRight(); |
turnAround(); |
|
putBall(); |
takeBall(); |
Writing a method is like teaching karel a new word.
Naming Methods: You can name your methods whatever you want, but you can't have spaces in the method name.
Remember that each open bracket { must match with a close bracket }
private void turnRight() { turnLeft(); turnLeft(); turnLeft(); } private void turnAround() { turnLeft(); turnLeft(); } private void yourMethodName() { // Code that will run when you make a call to // this method. }
if (condition)
{
//code that will run if the condition is true
}
if (condition)
{
//code that will run if the condition is true
}
else
{
//code that will run if condition is not true
}
if(frontIsClear()) { move(); } if(ballsPresent()) { takeBall(); } else { move(); }
()
at the end
frontIsClear() leftIsClear() rightIsClear() facingNorth() facingSouth() facingEast() facingWest() ballsPresent() |
frontIsBlocked() leftIsBlocked() rightIsBlocked() notFacingNorth() notFacingSouth() notFacingEast() notFacingWest() noBallsPresent() |
while (CONDITION) { // Code that will run while the CONDITION is true. // Once the CONDITION is no longer true, // it will stop. }
/* This moves Karel to a wall */ while(frontIsClear()) { move(); }
for (int i=0; i < COUNT; i++) { // Code that will run 'COUNT' times }
/* This puts down 10 balls */ for(int i = 0; i < 10; i++) { putBall(); }You can have multiple statements or function calls in a for loop.
/* This puts down five balls and moves after each one */ for(int i = 0; i < 5; i++) { putBall(); move(); }
/* A multi-line comment describes your code * to someone who is reading it. */ // Use single line comments to clarify code. /** * * A Javadoc comment * is used to describe how a * method or class works. * * It has two *'s on the first line. */
No slides available for this video
Admin Only. Not visible to customers
A collaborative program is a program you can work on with a partner or group of people. The program shows up in all of your sandbox pages, and when any of you save code, it will save it for each person.
Want to use your CodeHS code outside of CodeHS? Use this embed code to get started.
codehs.html
on your desktopcodehs.html
on your desktopJava (SuperKarel)