Monday, August 29, 2016

Learning Java: Command Line and LeJos

FIRST switched to Android Studio for robotics coding for the 2015-16 season.  Android Studio is a Java based platform used to create Apps for Android phones.  I spent part of last summer trying to get up to speed with Java.  Rather than dealing with Android Studio (which is a whole different can of worms), I worked with command line Java, and then with Java in NetBeans.

The command line programs described below are on GitHub at https://github.com/gcronin/LearningJava.

Program 1: Parabola
This program uses the scanner to take in  the coefficients of a parabola written in standard form, and converts to vertex form.












Here's an example of the output; the parabola y = x^2 + 2x + 5 is equivalent to y = (x+1)^2 + 4 with a vertex at (-1, 4).



Program 2: Distance Formula
Using the scanner again, the user inputs the x and y coordinates of two points, and the program calculates the distance between the points.









Here's an output showing that the distance between (0,0) and (1,1) is the square root of 2.





Program 3: Add Text to a File
This very simple program requires dealing with exceptions, which is a big part of Java.  When you open and write to a file, you must catch two exceptions... the first is given if the file doesn't exist, and the second is given if the program cannot write to the file.  We deal with exceptions by using the Try... Catch syntax.

A much more complex version of this program with user input can be found here (I didn't write it).



Using LeJos:  Java for NXT:
You can program a LEGO NXT in Java.  One of my students setup the compiler for me.  Once LeJos is installed on your computer, you first need to turn .java files into .class files using "nxjc".  Then you need to use "nxjlink" to create an "nxj" file from one of your class files.  Finally, you use "nxjupload" to upload the .nxj file.  In total, this series of commands will do the work for you:

nxjc *.java  //create .class files from .java files
set /p mclass= "Please enter the name of the main class file: " %=%  //chose a .class file
nxjlink -o linked.nxj %mclass%  //create linked.nxj from the .class file
nxjupload -r *nxj   //upload linked.nxj to the NXT


Here are a few Java programs for the NXT:
 This program just prints "Hello World" to the screen until any button is pressed.
This program shows the value of a light sensor attached to port 1 in several different formats.
This program moves motors attached to ports B and C at 50% power.
This program is a line follower using PID control.  I am not sure that it has been tuned correctly, as it was written by a former student.



No comments:

Post a Comment