Download Level H - Embedded Systems

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
ENIC4023 - Networked Embedded Systems Development
Console Applications Lab
1. Simple Hello World
Let's quickly edit, compile, and run our first java application and then look at how it works afterwards. Use your
favorite text editor (I recommend TextPad) to type in the following exactly (java is case sensitive):
public class HW {
public static void main(String[] arg) {
System.out.println("Hello There!");
}
}
Make a working directory and save the file as HW.java, again preserve the capitalisation. Open a command
prompt and change to your working directory. Enter the following command to compile your code:
javac HW.java
Notice that this creates a file HW.class, this is the java byte-code that will be interpreted by the java virtual
machine. To run the program enter:
java HW
OK let's make a few notes about what we have done:(a)
The name of the .java file must match the name of the public class it contains (case sensitive).
(b)
The class shown here contains a single method called main. This is the method that is run when a class
that is an application is started (similar to a main function in a C program). Here it contains a single
statement which outputs a message.
2. Passing information to the Program
Note from the code above that a single string array parameter called arg is passed to the main method. This
contains the command line parameters from the program invokation. This can be used to personalise the hello
program as shown:
public class HU {
public static void main(String[] arg) {
System.out.println("Hello " + arg[0]);
}
}
Save this in a suitably named file (remember note (a) above), compile it as above, this time supply a command
line argument when running it, eg:java HU Fred
This program only accepts a single command line argument, it would be nice to make the program more general
and accept any number of command line arguments that the user care to enter. This is easily acheived using a
simple loop:
public class HA {
public static void main(String[] arg) {
int i = 0;
while (i < arg.length) {
System.out.println("Hello " + arg[i]);
i++;
}
}
}
Test out this program with several arguments, eg:java HA Fred Joe Dave Filbert
These two programs illustrate some useful points:
(a)
An element of an array can be referenced using the array name followed by the element number in
square brackets. Like C, arrays in java always start with element 0 (zero).
(b)
In the context that it is used here the + operator concatenates strings, ie java supports operator
overloading.
(c)
The string array arg is an object and so has attributes and methods. One such is the length attrubute
which contains the number of elements in the array (which in our case is the same as the number of
command line arguments). Once the number of elements in the array is know it is a simple matter to
construct a loop to output them in turn.
(d)
The first version of the program requires that there be at least one element on the array. If there are
more than one it will use the first and ignore the rest. If there are none, the result will be a run-time
error, a situation that should be avoided. The second version avoids the run-time error as it will not
attempt to access the array if it has a zero length.
3. Interacting with the Program
We have seen in the above programs that it is easy to output lines of text to the console using
System.out.println( ... ), it works in a similar way to the puts( ... ) function in C.
Unfortunately there is nothing similar to the C gets( ... ) function in java. A program which allows the
user to enter a name to be output is shown:
import java.io.*;
public class HWho {
public static void main(String[] arg) {
String who = "who?";
InputStreamReader isr;
BufferedReader br;
System.out.print("Who you? ");
isr = new InputStreamReader(System.in);
br = new BufferedReader(isr);
try {
who = br.readLine();
} catch(Exception e) {
System.out.println("an error has ocurred during input");
} finally {
System.out.println("Hello " + who);
}
}
}
As can be seen, this is an altogether more complicated piece of code. It is not expected that you should
understand how all this works in detail yet but some significant points are:
(a)
The code uses some classes defined elsewhere (InputStreamReader, BufferedReader); the location of
these need to be made known to the compiler. This is done with the import statement. These classes,
along with many others, are contained in the java io package. Although they are not explicitly named in
the import statement, only those two classes will be imported and not all the others, ie java only brings
in what is needed. This is an improvement on the include directive of the C preprocessor.
(b)
Essentially the code takes the standard input stream System.in and wraps it in an
InputStreamReader object which is in turn wrapped in a BufferedReader object. The
readLine method of the BufferedReader object is then be used to read a line of text.
(c)
The readLine method of the BufferedReader class is capable of throwing an exception, ie it
may not always execute successfully. Java does not allow you to ignore this possibility. Hence the
try..catch..finally construct is used to handle this exception. the "risky" statement is put in
the try section. If, and only if, an exception occurs execution jumps to the catch section. The
finally section is always executed whether an exception occurs or not.
The above code can be tidied up by putting the code to input a line of text into a separate method and just calling
it when needed:
import java.io.*;
public class HWho2 {
public static void main(String[] arg) {
System.out.print("Who you? ");
System.out.println("Hello " + getInputLine());
}
public static String getInputLine() {
String who = "who?";
InputStreamReader isr;
BufferedReader br;
isr = new InputStreamReader(System.in);
br = new BufferedReader(isr);
try {
who = br.readLine();
} catch(Exception e) {
System.out.println("an error has ocurred during input");
} finally {
return who;
}
}
}
4. Using Separate Classes
A more flexible approach to that taken above would be to have the code to input a line of text as a separate class
in a separate file. This would make it easy to re-use in other applications. Consider writing a class called Stuff
that has the single method getInputLine(), the hello program would then just be:
public class HWho3 {
public static void main(String[] arg) {
System.out.print("Who you? ");
System.out.println("Hello " + Stuff.getInputLine());
}
}
The code for the class Stuff is stored in a separated file called Stuff.java. It must be compiled before the
code above. In theory the Stuff.class file that results from the compilation could be in any directory but
this would require appropriate classpaths to be set up for any compilations that used it and for running the
resultant application. This is a can-of-worms best left for another day. For now edit and compile the Stuff
class in the same directory as the HWho3 object. The code for the Stuff class is shown:
import java.io.*;
public class Stuff {
public static String getInputLine() {
String who = "who?";
InputStreamReader isr;
BufferedReader br;
isr = new InputStreamReader(System.in);
br = new BufferedReader(isr);
try {
who = br.readLine();
} catch(Exception e) {
System.out.println("an error has ocurred during input");
} finally {
return who;
}
}
}
5. Doing Some Arithmetic
Most useful applications input some information, process that information, and output the results of that
processing. An example would be an application that does some simple arithmetic:
public class Arith {
public static void main (String[] arg) {
//local variables
float x = 0;
float y = 0;
float sum = 0;
float diff = 0;
float prod = 0;
float div = 0;
//input info
System.out.print("input first number: ");
x = Float.parseFloat(Stuff.getInputLine());
System.out.print("input second number: ");
y = Float.parseFloat(Stuff.getInputLine());
//process info
sum = x + y;
diff = x - y;
prod = x * y;
div = x / y;
//output info
System.out.println("sum of
System.out.println("diff from
System.out.println("product of
System.out.println("division of
}
}
Notes:
"+x+"
"+x+"
"+x+"
"+x+"
and
to
and
by
"+y+"
"+y+"
"+y+"
"+y+"
is
is
is
is
"+sum);
"+diff);
"+prod);
"+div);
(a)
Note the use of the getInputLine method from the Stuff object developed before. A
Stuff.class file should be compiled into the same directory as the Arith object.
(b)
The return value of the getInputLine method is of type String. To do arithmetic we need an
arithmetic type such as float. The parseFloat method of the Float Class in the java.lang
package is used to do this. Note that the java.lang package is implicitly imported into all applications so
no explicit import statement is required. The actual object that the method is from has to be specified in
the code because other objects in the java.lang package also have parseFloat methods.
At first sight the valueOf method of the Float class would seem to also be a way of converting from
a string to a float. This is not the case: valueOf returns a Float, this is a wrapper class for a float
primative, and is therefore different.
6. Exercise
Write an application in java to input a positive integer and test if it is divisble by 2, 3, or 5 and print out the
results. The application should continue prompting for more numbers until the value zero is entered, at which
point it should exit.
For Interest
On this module we will be using a subset of Java chosen to suit network programming. If we don't need to cover
a topic we won't. Introductory books on Java cover a very different subset of Java; they have topics that we do
not cover. Notably we will not cover GUIs (Graphical User Interfaces); most books devote a lot of space to this.
If you really want the output of your program to look "pretty", the following sample code illustrates an
alternative way of achieving this.
It uses the JEditorPane class from the javax.swing library. This effectively creates a window that renders HTML.
Thus if we know how to write HTML that creates a "pretty" page, we can display it for the user using
JEditorPane. Try out the sample code which just lists the command line arguments passed to it. Explanation of
the code will be left to (much) later, for now just see that such things are possible.
import javax.swing.*;
public class Pane {
public static void main(String[] args) {
if (args.length > 0) {
StringBuffer text =new StringBuffer("<HTML><BODY>");
text.append(
"<H2 color='navy'>Arguments Supplied to Program</H2><OL>");
for (int i = 0; i < args.length; i++) {
text.append("<LI color='red'>" + args[i]);
}
text.append("</OL></BODY></HTML>");
JEditorPane jep = new JEditorPane("text/html", text.toString());
jep.setEditable(false);
JScrollPane scrollPane = new JScrollPane(jep);
JFrame f = new JFrame("Program Arguments");
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
f.setContentPane(scrollPane);
f.setSize(512,342);
f.show();
} else System.out.println("Usage: java Pane [arg1, arg2, ....]");
}
}