You are on page 1of 16

Java Programming with leJOS Problem Solving with Robots [PRSOCO601]

Thomas Devine http://www.noucamp.org thomas.devine@lyit.ie April 14, 2008

Contents
1 2 3 4 5 6 7 8 Background Hello, world! Classes Objects Class versus object 5 5 6 6 7 7 8 9

import

Package Statements

Methods Static Methods

8.1 leJOS static methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .


TriBot Class

10 11

10 Constructors

10.1 Default Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 10.2 TriBot constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 10.3 Overloaded Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 11.1 TouchSensor Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 11.2 SoundSensor Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 11.3 UltrasonicSensor Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
15 14

11 Sensors

12 Arrays

List of Figures

Song Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Listings

1 2 3 4 5 6 7 8 9 10

HelloWorld.java . . . . Song.java . . . . . . . StaticMethod.java . . . TriBot.java . . . . . . TriBotProgram.java . . TriBot.java . . . . . . TriBot.java . . . . . . TouchSensor Class . . SoundSensor Class . . UltrasonicSensor Class

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

5 6 9 10 11 12 13 14 15 15

Background

This document introduces the fundamentals of Java object-oriented programming that need to be understood to program the Lego NXT. These notes are not intended to be as comprehensive as those you will receive in the main Object-Oriented Programming module. From time to time you may be introduced to concepts not previously covered in the main ObjectOriented Programming module. This is something you must accept so progress can be made in this module.
2 Hello, world!

Listing 1 shows the classic rst program written in many programming languages { Hello World. Listing 1: HelloWorld.java
1 2 3 4 5 6 7 8

import lejos . nxt . LCD ; public class HelloWorld { public static void main ( String [] args ) { LCD . drawString (" hello , world !" ,0 ,0); LCD . refresh (); } }

The program prints the text "hello, world!" on the NXT LCD. It demonstrates some basic concepts you must have seen before. We'll explain it brie y now. For now, we'll ignore the import statement in the rst line. We'll explain it later. Line three contains a statement that de nes the class name, in this example, HelloWorld. Note the curly brace located after the class declaration and the matching curly brace located at the end of the le. All of the methods and variables contained in the class must lie within these two curly braces, otherwise it will not compile. Line four contains a method de nition. As you can see, methods also use curly braces. This method is named main(). The main() method is the starting point for all Java programs. All leJOS programs are started using a main() method. There are other keywords in the method de nition { public, static, and void. For now, the only thing you should know is that these must be present for the main() method to function properly. There are also some words in parentheses (round brackets) after the method name, the signi cance of which will be explained later too. The statements within the main() method are code of the program; they provide the functionality of the class. The rst line outputs the word "hello, world!" to the LCD display. The next line asks the LCD to refresh so the text "hello, world!" is shown on the LCD. The program will ash "hello, world!" for a brief millisecond and then end.

Classes

Classes are programming structures that de ne objects. They are like templates that are used to create objects, typically by using the new keyword. One class can make a multitude of objects, much like a rubber stamp can create copies of the same design. For example, String is a Java de ned class contained in the java.lang package. In order to create several String objects, we can use the code:String s1 = new String("String A"); String s2 = new String("String B"); String s3 = new String("String C");

When you design your own classes you need to think about the data any object instance needs to know about itself and the methods that will operate on that data. Figure 1 shows the Song class design we could create.

Figure 1: Song Class Listing 2 shows how it would be implemented in Java code. Listing 2: Song.java
1 2 3 4 5 6 7 8 9 10 11

public class Song { String title ; String artist ; void setTitle ( String title ){ this . title = title ; } void setArtist ( String artist ){ this . artist = artist ; }

Objects

An object is an instance of a class that contains the class variables and methods. Objects form the basis of object-oriented programming. Put another way, they contain the data and functionality of a class. 6

A class is not a object, but a programmer can use a class to create an object by using the new keyword to call a constructor on the class. The new object is usually assigned to a object variable if the object needs to be referenced in later lines of code. The following code shows a String object being created with the new keyword, initialised with text "Lego" and assigned to a object variable called name:String name = new String ("Lego");

Once an instance of an object is created, it is possible to call methods on that object or access variables. The following line of code uses the lenght() method to retrieve the length of the String object created above:int length = name.length();

This is the essence of object-oriented programming. Objects contain all the data and methods they require in one place. This makes the code easier to understand, especially when compared to structured programming where methods and data are thrown together. The following code shows the Song class (mentioned earlier) being used to create a object mySong and methods being called:Song mySong = new Song(); mySong.setTitle("Hurt"); mySong.setArtist("Johnny Cash"); mySong.play();

Class versus object

A class is not an object, but it's used to construct them. A class is a blueprint for an object. It tells the virtual machine how to make an object of that particular type. Each object made from that class can have its own values for the instance variables of that class. For example, you might use the Button class to make dozens of di erent buttons, and each button might have its own color, size, shape, label, and so on. But remember, there will only be one Button class.
6

import

Package Statements

You may have noticed the following statement at the top of the HelloWorld class:import lejos.nxt.LCD;

This is an import statement responsible for allowing the HelloWorld class to access the single class LCD, contained in the lejos.nxt package. We could have used this line instead:import lejos.nxt.*;

This import statement allows the HelloWorld class to access ALL classes contained in the lejos.nxt package. This does not cause all these classes to load into memory. Only the classes used in your code loaded. The lejos.nxt package contains an assortment of classes that perform functions according to the theme of the package. The main theme of the lejos.nxt package is that all the classes give you access to the NXT platform. These classes can not be accessed by your code until the import statement is used. NOTE { The java.lang package is always imported automatically by Java. This is because the classes used in this package are central to the use of the Java language. It contains such important classes as System, String and Math which are used frequently.
7 Methods

A method gives a class it's functionality. All methods must be contained within a class. Methods have two important de ning characteristics { return types and arguments. Let's examine a typical Java method de nition:public double pi() { return 3.14159265; }

The rst line of this method declares a return type of double, so by de nition the code within the curly braces must return a double value. If a method declares it will return a value but the code does not return anything, the compiler will produce an error. Methods can just as easily return objects too. As you can see above, the parentheses (round brackets) are empty and contain no arguments (or parameters). Let's examine a method that uses arguments:public int sqr(int value) { return value*value; }

The above method has a return type of int, so the code in the curly braces must return an int value. This method uses one argument (or parameter) value. Arguments can be objects too. This method returns a integer value (value*value). Finally, a method does not have to return any value. In this case the method return type would be declared void. For example:public void printHello() { System.out.println("hello"); }

Static Methods

A static method is a method that can be called without creating an instance of a class. There are a number of static classes de ned within Java. These methods are static because they produce the same result every time. To contrast static methods with class methods, lets examine the following code.
String str = new String("Lego"); int length = str.length(); System.out.println("length="+number);

The code above demonstrates how a method is normally called from an object. The object reference str is created from the class String. The str object could though be given any string value. Therefore length() could return di erent integer values depending on the string. With static methods, however, there is no need to create an instance rst. For example we can use a static method round() from the Math class to do this:System.out.println("3.14 rounded = " + Math.round(3.14));

There are many Java classes, such as the Math, that contain exclusively static methods. Since no data needs to be kept in an object for Math methods to work, there is no reason to go to the trouble of creating an instance of Math.
8.1 leJOS static methods

There are many leJOS Java classes, such as the lejos.nxt.Motor, that contain static methods. So, there is no reason to go to the trouble of creating an instance of Motor. For example, we can make a motor A move forward by using the code:Motor.A.forward();

It is easy to use static methods, but we will write our own classes that encapsulate them into a traditional class/object model later. Listing 3 shows how we could create our own static method called waitSeconds(). Listing 3: StaticMethod.java
1 2 3 4 5 6 7 8 9 10

import lejos . nxt .*; public class StaticMethod { public static void waitSeconds ( int seconds ){ try { Thread . sleep ( seconds *1000); } catch ( Exception e ){ // do nothing for now

11 12 13 14 15 16 17 18 19

public static void main ( String [] args ) { LCD . drawString (" hello " , 0, 0); LCD . refresh (); waitSeconds (2); }

The waitSecounds() method is declared in lines 5{12 and called from main() at line 17. waitSeconds() is passed an integer value { seconds, that is used determine how long the method will sleep. Also, waitSeconds() returns no value, hence the use of the reserved word void.
9 TriBot Class

We will write a reusable TriBot class called TriBot.java, that will implement functionality associated with the Lego tribot we have built. Listing 4 shows how we could implement the TriBot class with just one functional method { forward(). Listing 4: TriBot.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

import lejos . nxt .*; public class TriBot { private void waitSeconds ( int seconds ) { try { Thread . sleep ( seconds *1000); } catch ( Exception e ){ // do nothing for now } } public void forward ( int seconds ) { Motor .B. forward (); Motor .C. forward (); waitSeconds ( seconds ); }

Once this class is written we can access it in any Java program that wants to use it (and that can see it). Listing 5 shows how our new TriBot class can be used. The TriBot class illustrates all the bene ts of object-oriented programming { reusable, reliable, extendible, robust, and maintainable. 10

Listing 5: TriBotProgram.java
1 2 3 4 5 6 7 8

public class TriBotProgram { public static void main ( String [] args ) { TriBot tribot = new TriBot (); tribot . forward (3); } }

10

Constructors

A constructor is the code that runs when you create a object using the new keyword. Here is the code that creates a tribot object:TriBot tribot = new TriBot();

When this code is executed Java calls the TriBot constructor method { TriBot(). The only way to call the constructor is with the new keyword. A constructor looks like a method (because of its round brackets) but it isn't.
10.1 Default Constructors

Listing 4 shows our TriBot class. But the constructor TriBot() is missing. It only has two methods { waitSeconds() and forward(). So where is the constructor TriBot()? You normally write the constructor for your own classes (we will do this in a moment), but if you don't, the Java compiler writes a default one for you! Here is what the default constructor for the TriBot class looks like:public TriBot() { }

It's got no code within the braces. So, earlier when we did not specify a constructor for the TriBot class, Java provided this default one when it compiled the class. This and any constructor has :  

the same name as the class; a public access speci cation; no return type.

11

10.2

TriBot

constructor

The key point of a constructor is that it has code that is executed immediately when the object is created. This means you get a chance to setup the object before it is used in any subsequent method calls. In our TriBot class we would like to setup the tribot with the following initial properties: 

use a a default speed of 200 degrees per second; reset the tachometer count to 0 (zero). Listing 6: TriBot.java

Listing 6 shows the code necessary for the TriBot class constructor.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

import lejos . nxt .*; public class TriBot { public TriBot () { // set default speed for both motors Motor .B. setSpeed (200); Motor .C. setSpeed (200); // reset tachometer for both motors Motor .B. resetTachoCount (); Motor .C. resetTachoCount ();

private void waitSeconds ( int seconds ) { . . . . . . } public void forward ( int seconds ) { . . . . . . }

Now, when a tribot object is created with code (below) the TriBot() constructor is called and motors are given a default speed of 200 degress per second and have their tachometers reset to zero.
TriBot tribot = new TriBot();

12

10.3

Overloaded Constructors

Constructors are ideal locations for initialising the state of a object. In our example we set the default speed and reset the tachometers. Everytime a new TriBot object is created it is given a default speed of 200 degrees per second. That's all well and good. But what if the programmer wants to set a inital speed of 800 for the TibBot. For example, using our existing code if the programmer wanted the TriBot speed to be 800, here is the code to do this:TriBot tribot = new TriBot(); tribot.setSpeed(800);

What actually happens here is the motor speed is being set twice:1. the constructor sets the default speed to 200; 2. the setSpeed() method sets the speed to 800. Ideally, we would like to let the programmer make a new TriBot and set the TriBot speed all in one call. This can be done by creating a constructor with parameters. Listing 7 shows the code necessary for a second TriBot class constructor. Notice how the local variable speed is used in the second constructor. Listing 7: TriBot.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

import lejos . nxt .*; public class TriBot { public TriBot () { // set default speed for both motors Motor .B. setSpeed (200); Motor .C. setSpeed (200); // reset tachometer for both motors Motor .B. resetTachoCount (); Motor .C. resetTachoCount ();

public TriBot ( int speed ) { // set default speed for both motors Motor .B. setSpeed ( speed ); Motor .C. setSpeed ( speed ); // reset tachometer for both motors Motor .B. resetTachoCount (); Motor .C. resetTachoCount ();

13

27 28 29 30

. . . . . . . . .

Below, you can create a tribot object and give it a default speed of 800 degress per second with one call.
TriBot tribot = new TriBot(800);

If you have more than one constructor in a class, it means you have overloaded constructors.
11
11.1

Sensors

TouchSensor

Class

The TouchSensor class allows access to the basic NXT touch sensor. The sensor has a simple switch that is activated by the orange button on the front. The TouchSensor class has a constructor TouchSensor(SensorPort port) and method boolean isPressed().
TouchSensor(SensorPort port) creates a touch sensor object attached to the speci ed port. The ports labelled one to four are represented respectively by SensorPort.S1, SensorPort.S2, SensorPort.S3, and SensorPort.S4. boolean isPressed() checks if the sensor is pressed.

Listing 8 shows how a touch sensor can be programmed. Listing 8: TouchSensor Class
1 2 3 4 5

TouchSensor ts = new TouchSensor ( SensorPort . S1 ); while ( ts . isPressed ()== false ) { // doing nothing }

11.2

SoundSensor

Class

The SoundSensor class allows access to the LEGO sound sensor which measures the loudness of sound in decibels. It has two modes of operation, dB and dBA mode. dB mode measures decibels, while dBA measures a sound intensity for the range of human hearing. The default mode is dB. The SoundSensor class has a constructor SoundSensor(SensorPort port) and a method int readValue().
SoundSensor(SensorPort port) creates a sound sensor object attached to the speci ed

port.

14

int readValue() reads the current sensor value as a percentage.

Listing 9 shows how a sound sensor can be programmed. Listing 9: SoundSensor Class
1 2 3 4 5 6 7

SoundSensor ss = new SoundSensor ( SensorPort . S2 ); TriBot tribot = new TriBot (300); tribot . forward (); while ( ss . readValue () <600) { } tribot . stop ();

11.3

UltrasonicSensor

Class

The UltrasonicSensor class allows access to the LEGO ultra sonic sensor which measures the distance to objects. The UltrasonicSensor class has a constructor UltrasonicSensor(SensorPort port) and a method int getDistance().
UltrasonicSensor(SensorPort port) creates a ultra sonic sensor object attached to the

speci ed port.

int getDistance() reads the distance to a object. If no object is in range it returns 255.

Listing 10 shows how a ultra sonic sensor can be programmed. Listing 10: UltrasonicSensor Class
1 2 3 4 5 6 7

UltrasonicSensor us = new UltrasonicSensor ( SensorPort . S3 ); TriBot tribot = new TriBot (300); tribot . forward (); while ( us . getDistance ()!=255) { } tribot . stop ();

12

Arrays

An array is a collection of primitive data types (or objects). For example, an array could hold a collection of temperatures or a collection of student names. You can create an array in much the same way as a object. Here is how to create an array of six integers:
int[] lotto = new int[6];

Array creation is a two stage process: 1. int[] lotto declares a object reference called lotto for a integer array. 15

2. new int[6] creates space in memory for the six integers. Once the array is created its elements can be accessed like any other variable, however a index is used to access each speci c element. For example, here is how to assign a value to the rst lotto array element:
lotto[0]=6;

The rst thing to notice is that array indices begin at 0 (zero), not 1 (one). Here is how to assign values to all the other lotto array elements:
lotto[0]=6; lotto[1]=12; lotto[2]=18; lotto[3]=24; lotto[4]=30; lotto[5]=36;

Once the array has been assigned values they can be accessed again using the array name and index. For example, here is how to print all the lotto array values:
for(int i=0;i<6;i++) System.out.println(lotto[i]);

16

You might also like