Writing your first leJOS NXJ program


Writing your first leJOS NXJ program

The HelloWorld program

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


      public class HelloWorld
      {
      }
      

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


      public class HelloWorld {
        public static void main (String[] args) {
        }
      }
      

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


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

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 leJOS web site here and included in the leJOS download in the docs folder of the classes project.

The complete HelloWorld program is:


      import lejos.nxt.*;
      
      public class HelloWorld {
        public static void main (String[] args) {
          System.out.println("Hello World");
          Button.waitForPress();
        }
      }
      

Read the next section to learn how to compile and run this program

Back to top