Download Console Application Development

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
COMP2059 - Sun Certified Java Programmer
Console Application Development
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 (eg NotePad++, TextPad, or JEDPlus) to type in the
following exactly (java is case sensitive):
public class HW {
public static void main(String[] args) {
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 args is passed to the main
method. This contains the command line parameters from the program invocation. This can be used
to personalise the hello program as shown:
public class HU {
public static void main(String[] args) {
System.out.println("Hello " + args[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[] args) {
int i = 0;
while (i < args.length) {
System.out.println("Hello " + args[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 args is an object and so has attributes and methods. One such is the length
attribute 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 is 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.
(e)
As of Java 5, a new feature called var-args was added to the language. See "Methods with
Variable Argument Lists" (p46-47) in the study guide for details. Using var-args the main
method can alternatively be written as:
public static void main (String... args) {
}
This still passes an array of Strings named args to the main method and the elements of the
array are accessed the same as before.
3. 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[] args) {
if (args.length == 2) {
//local variables
float x = Float.parseFloat(args[0]);
float y = Float.parseFloat(args[1]);
float sum, diff, prod, div;
//process info
sum = x + y;
diff = x - y;
prod = x * y;
div = x / y;
//output info
System.out.println(x + " +
System.out.println(x + " System.out.println(x + " *
System.out.println(x + " /
} else {
System.out.println("Usage:
}
"
"
"
"
+
+
+
+
y
y
y
y
+
+
+
+
"
"
"
"
=
=
=
=
"
"
"
"
+
+
+
+
sum);
diff);
prod);
div);
}
java Arith A B");
}
}
Notes:
(a)
The command line arguments are available to the main method in an array 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 primitive, and is therefore different.
See the section on "Using Wrapper Conversion Utilities" (p230-233) in the study guide for a
detailed explanation.
Sample output from the above application is shown below, notice a problem?
The format of the numeric values being output is not under our control when using
System.out.println. System.out is an object of PrintStream class. Java 5 added extra
methods to this class to allow formatting of output. These are the format() and printf()
methods. These two methods are actually identical in all but name and so can be used
interchangeably.
Replace the 4 statements that output the information in the code above with:
//output info
System.out.format("%.2f
System.out.format("%.2f
System.out.format("%.2f
System.out.format("%.2f
+
*
/
%.2f
%.2f
%.2f
%.2f
=
=
=
=
%.2f\n",
%.2f\n",
%.2f\n",
%.2f\n",
x,
x,
x,
x,
y,
y,
y,
y,
sum);
diff);
prod);
div);
The output should now look like this:
See the section on "Formatting with printf() and format()" (p489-491) in the study guide for a
detailed explanation. Experiment by formatting the output differently (eg try using a width
specifier).
4. Exercise
Write an application in java to input a positive integer and test if it is divisible 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.
5. Head First Java - "Be the Compiler"
The exercises in this book (see module website for purchasing details) are very good. These are
taken from page 21 (2e).
Each of the three Java files that follow represents a complete source file. Your job is to first play
compiler and determine whether each of these files will compile. If they won't compile, fix them!
The play JVM and determine if they run sensibly, if not fix them!
A
B
C
class ExerciseA {
public static void main(String[] args) {
int x = 1;
while (x < 10) {
if (x > 3) {
System.out.println("big x");
}
}
}
}
public static void main(String[] args) {
int x = 5;
while (x > 1) {
x = x - 1;
if (x < 3) {
System.out.println("small x");
}
}
}
class ExerciseC {
int x = 5;
while (x > 1) {
x = x - 1;
if (x < 3) {
System.out.println("small x");
}
}
}
6. Just for Interest
(not in SCJP exam)
On this module we will be using the subset of Java that is in the SCJP exam. If we don't need to
cover a topic we won't. Introductory books on Java often cover a different subset of Java. Notably
we will not cover GUIs (Graphical User Interfaces); many 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, ....]");
}
}