Skip to main content

Writing your first program

Posted in

This tutorial results from the official leJos web site.

Let us start with a simple “Hello World” program. We will create a HelloWorld class in the default java package:

  1. public class HelloWorld
  2. {
  3. }

leJosRT requires the standard main method for the program entry point:

  1. public class HelloWorld {
  2. public static void main (String[] args) {
  3. }
  4. }

LeJosRT, as leJOS NXJ, supports the standard java System.out.println method and scroll the output on the NXT LCD screen.

  1. public class HelloWorld {
  2. public static void main (String[] args) {
  3. System.out.println("Hello World");
  4. }
  5. }

If you run this program as it is, it will display "Hello World” and then immediately return to the menu, so you will not be able to see what is displayed (unless you are very quick). We either need the program to sleep for a while to allow the text to be read, or to wait for a button to be pressed. Let us wait for a button to be pressed. To do this we need to include the leJOS NXJ Button class in the program. Button is in the lejos.nxt package. We can either include lejos.nxt.Button or lejos.nxt.* to allow any of the standard lejos.nxt classes to be used in the program. The Button class has a method waitForPress() that waits for any button to be pressed. You can find out what methods a class supports by looking at the API documentation. The API documentation is on the leJosRT web site here. The complete HelloWorld program is:

  1. import lejos.nxt.*;
  2.  
  3. public class HelloWorld {
  4. public static void main (String[] args) {
  5. System.out.println("Hello World");
  6. Button.waitForPress();
  7. }
  8. }

Read another tutorial to learn how to compile and run this program.