CSCI213
Autumn Session, 2007
Lab Exercise 1
This exercise is intended to help you get used to the Java development environment before you start assignment 1. It has lots of parts with little programs; you should enter and run each of these example programs so as to gain experience with the Java environment.
Laboratory classes for CSCI213 are normally held in the "Java" lab. in building 3. This lab. (3.229) is equipped with Dell workstations configured for either Linux or Windows use. We will run them in Windows mode.
(Well, that was what was promised! But the updating of the laboratory didn't take place. So we are to move to a different lab. Hope things work there!)
Although an attempt is made at the start of session to allocate you to specific lab. classes, this allocation is not that important. All that matters is that you don't all try to use the lab. at the same time. There is no permanent association between your lab. class and the tutor who will mark your submissions - all submissions are pooled and randomly allocated to markers.
You will be able to do most of your work on your own computer if you prefer. You will have to install some software - Java systems and usually a database system. The best way to work is to duplicate, as far as is practical, the laboratory environment on your own computer and then do preliminary work on your own computer coming to the labs with partly completed programs that you can then reference when discussing any problems with a lab-tutor.
You will need a USB flash-drive to store your code. When developing code at a workstation, you arrange that the necessary files are kept on your flash drive. Do not leave any files on the laboratory workstations.
We use the JDK 1.5 ("Java 5") dialect of Java. The older JDK (Java Development Kit) 1.4 dialect is still quite commonly deployed. Most of the books in the library will use JDK 1.4 or older dialects of Java; all books now in bookstores will use JDK 1.5.
In previous years, we have used the simple JDK environment for development.
With the JDK, you use an ordinary text editor when preparing code, and you work at
the command line (cmd.exe in Windows) using commands like javac
to compile Java and java to run programs.
We will be using Sun's NetBeans 5 development environment. This should be installed on the workstations in 3.229. You can download the latest version from Sun for your own use; to save download costs, there is a copy on the banshee Unix machine in the /share/cs-pub/csci213 directory (you can access this directory via secure ftp or when logged in on a Unix terminal in one of the labs in building 17.)
(Again, the fact that the lab has not been updated may stop the planned switch to using NetBeans. The assignments as set assume NetBeans to be available and many of examples in lecture notes have been changed to take advantage of NetBeans. If it proves impractical to use NetBeans in the alternate lab then the old lecture notes can be put back; some parts of the assignments will need to be changed - Assignment 2 currently is set to use the NetBeans tool that helps create JavaDoc documentation, a task that is too painful to do without good tool support.)
NetBeans has been around for several years but it used to be very SLOW. Possibly the current version of NetBeans is better, more likely it is simply that current machines are so much faster. The current NetBeans is quite usable.
An integrated development environment like NetBeans has several advantages:
packages (class libraries).
This copy allows the editor to assist you in tasks like adding the right
import statements (similar to #include statements in C++) and
in checking function signatures so as to prompt you to supply the correct
arguments.breakpoints that pause execution allowing you to check
the values of variables at specific points in the program's execution.Such features generally improve your productivity - you will find it easier to get your programs to compile and run correctly when using an integrated development environment as compared with conventional editor/command-line environments.
The disadvantage of an integrated development environment is that you
must learn to use its features. In the initial stages, it is more complex
than the simpler environment of text-editor and javac, java
commands.
javac
(compiler) and java (execution system) tools that are used
when developing without an IDE.API links to open a window to the class documentation
(Internet Explorer may raise a security dialog asking whether you want
to activate a feature on the documentation page - give IE permission to
activate the control). The API web page lists the names of all the
classes as hypertext links; clicking a link results in display of information
about a particular class (the information always includes a list of methods,
sometimes there is introductory material explaining the use of the class
and providing example code).File/New Project menu option to bring up a dialog
that lets you define a new project. Select "Java Application" as the project
type:main()
function; we won't be creating any HelloWorld objects.// TODO code application logic here with the line
System.out.println("HelloWorld");
File/Save menu command to save your edits.
Build/Compile "HelloWorld.java"
menu command to compile the code. It should compile without
errors:Run/Run Main Project menu command to
run the program. The output window should display the results
init: deps-jar: compile: run: HelloWorld BUILD SUCCESSFUL (total time: 1 second)(The program output from this little program - HelloWorld - is almost lost among all the administration output that lists the steps taken and the total time.)
HelloWorldDemo project in the Projects
pane of the NetBeans window (the line with the coffee cup icon). Then use
either the File/Close Project menu option, or the pop-up "close
project" option you get with a right click.File/Exit to terminate the NetBeans session.
File/Open Project menu option
to get a dialog that lets you find and re-open a project:
public class HelloWorld {
public static void main(String[] args) {
String name = null;
if(args.length==0) name = "nobody";
else name = args[0];
System.out.println("Hello " +
name );
}
}
Arrays, like the array args here, have a read-only
data member length. The if test checks whether
there were any command line arguments provided (array would have a size
greater than zero if there were some arguments). If there were arguments,
the code takes the first as the name of a person to be greeted. (The
first argument is in element [0] of the array; like C++, Java starts its
arrays with element 0).
"Hello " + nameuses String concatenation to build a new String object that contains the value of name appended to the constant "Hello ". String concatenation is only one of many, many things that you can do with Strings (just look at the String section in the class documentation to find out some more things you can do.)
System.out.println("HelloWorld");
from the HelloWorld main() and use copy-and-paste to transfer the following
code into the main() function.
Sting name = null;
if(arg.length==0) name = "nobody"
else name = args[0];
System.out.prinln("Hello +
name );
If you paste that code in exactly as shown, the NetBeans editor should
(after a momentary delay) highlight a couple of the errors with red check-
marks in the left margin. If you move the mouse over a check-mark, a
pop-up window will appear with an explanation of the error."Hello , and the missing semi-colon (;) after nobody.
File/Save to
save the updated program.
javac compiled Java file with
the java command, it is easy to supply any command line
arguments, e.g. java HelloWorld Homer Simpsonresults in
Homer being in args[0] and
Simpson being in args[1].
Properties to get the properties dialog.
Properties dialog, pick the Run Category:
Arguments text field.
public class HelloWorld {
public static void main(String[] args) {
BufferedReader input = new BufferedReader(
new InputStreamReader( System.in));
System.out.print("Who are you? ");
String name = null;
try {
name = input.readLine();
}
catch(Exception e) {
System.out.println("Couldn't read from keyboard because"
+ e);
System.exit(1);
}
System.out.println("Hello " + name);
}
}
Here we can no longer rely purely on defaults. We want to use some
stream filter classes - InputStreamReader, BufferedReader - that aren't
in the basic java.lang package.
import statements
at the start of your program. You can import classes individually with
specific imports like:
import java.io.BufferedReader;Often, it's easier to import the entire package:
import java.io.*;
Source/Fix imports command to fix up the imports. (Of
course, NetBeans has to guess which class you mean. It finds only one BufferedReader
among the standard classes, so it guesses correctly that you mean java.io.BufferedReader.
Sometimes, there are classes of the same name in different packages - NetBeans
finds this confusing and will usually put up a dialog asking which you mean.
Occassionally, NetBeans simply makes an incorrect guess and adds the wrong
import statement. You can always fix the import statements manually.) In
this case, NetBeans guesses correctly and adds a couple of import statements
that you will find at the start of the HelloWorld.java file:
package helloworlddemo; import java.io.BufferedReader; import java.io.InputStreamReader;Once you have fixed the imports, save the file and read through the code.
System.in object; yeeech. Clumsy, but you will
soon get used to this stuff.) Then we print a prompt, and want to read a
user input.
Output pane in the NetBeans window;
you type input into this text entry field. Your prompt probably hasn't appeared
before you need to supply input.)
public class HelloWorld {
public static void main(String[] args) {
BufferedReader input = new BufferedReader(
new InputStreamReader( System.in));
System.out.print("How many hellos do you want? ");
int number = 0;
try {
String data = input.readLine();
number = Integer.parseInt(data);
}
catch(Exception e) {
System.out.println("Couldn't read from keyboard because"
+ e);
System.exit(1);
}
for(int i=0;i<number;i++)
System.out.println("Hello World");
}
}
Here we use a static member function in class Integer to do the
parsing of the String "data" into an integer value. (It is a static
member function, so we don't need to create an instance of class Integer
and ask an Integer object to do the parsing).
You can check the definition of the function in the Java API documentation:
java
command at the command line interface).
init: deps-jar: Compiling 1 source file to G:\213Examples\Greetings\HelloWorldDemo\build\classes compile: run: 6 How many hellos do you want? Hello World Hello World Hello World Hello World Hello World Hello World BUILD SUCCESSFUL (total time: 6 seconds)
HelloWorldDemo project and all its files.
WordCounts project, located in a different
subdirectory of your 213Examples directory.
StringTokenizer. If you look up
StringTokenizer you will find an explanation of how it works
and the following example code fragment:
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
This creates a tokenizer to work on the constant string "this is a test".
It will split the string into individual words ("this", "is", ...); by
default, string tokenizers split at white space characters.
String aLine = input.readLine();
String[] words = aLine.split("[^a-zA-Z]");
the regular expression [^a-zA-Z] specifies that all non-alphabetic characters
are substring terminators.
[...] square brackets delimit a group of characters ^ here, the ^ character means "complement", the characters that we are interested in are anything other than those listed following the ^ character a-z a character range, all lower case letters A-Z a character range, all upper case lettersSo the expression says all characters that are NOT lower case or upper case letters, i.e. digits, punctuation marks etc. OK?)
try {...} catch{...} block above. The
code says read in a line, but don't store its value! The code should
have been
try {
line = input.readLine();
}
catch(IOException ioe) { ... }
You will soon be meeting many such run-time errors!
line was initialized to null and never
got set to reference an actual string. When execution reached the statement
with line.split("[^a-zA-Z"]) the Java interpreter tried to use the value in
line to determine which string to split. But there was
no value in line, hence the NullPointerException.)
public class Words {
public static void main(String[] args) {
BufferedReader input = new BufferedReader(
new InputStreamReader( System.in));
LinkedList<String> wordList = new LinkedList<String>();
for(;;) {
System.out.println("next line");
String line;
try {
line = input.readLine();
}
catch(Exception e) { break; }
if(line.equals("Quit")) break;
if("quit".equals(line)) break;
System.out.println("\t"+line);
String[] words = line.split("[^a-zA-Z]");
for(String word: words){
if(word.equals("")) continue;
word = word.toLowerCase();
if(wordList.contains(word)) continue;
wordList.add(word);
}
}
Collections.sort(wordList);
System.out.println("Unique words");
for(String word: wordList)
System.out.println(word);
}
}
public class Words {
private static LinkedList<String> wordList ;
private static BufferedReader input;
private static void initialize()
{
input = new BufferedReader(
new InputStreamReader( System.in));
wordList = new LinkedList<String>();
}
private static void readData()
{
for(;;) {
System.out.println("next line");
String line;
try {
line = input.readLine();
}
catch(Exception e) { break; }
if(line.equals("Quit")) break;
if("quit".equals(line)) break;
System.out.println("\t"+line);
String[] words = line.split("[^a-zA-Z]");
for(String word: words){
if(word.equals("")) continue;
word = word.toLowerCase();
if(wordList.contains(word)) continue;
wordList.add(word);
}
}
}
private static void generateReport()
{
Collections.sort(wordList);
System.out.println("Unique words");
for(String word: wordList)
System.out.println(word);
}
public static void main(String[] args)
{
initialize();
readData();
generateReport();
}
}
Make certain that you understand the use of the "static" data members
and "static" member functions.
private for they are
used only from within other (public) functions defined in the class.
Here they have to be static, this is still procedural style
code.
readLine() function will return null
when you have reached the end of file. Your code should use
this condition to terminate input.
G:/213Examples/WordsProject/WordCounts/datafiles/data.txtor
G:\\213Examples\\WordsProject\\WordCounts\\datafiles\\data.txtNote, if you supply a Windows style pathname for a file, you should double every back-slash character in the string (actually, with NetBeans it doesn't matter - NetBeans fixes up the paths; but generally Java programs don't like Window's style pathnames because a backslash character in a String is normally an escape character).
ps2pdf command. ps2pdf is not
a supported Sun program. It appears to work but might have problems with complex
files. (You can get a postscript file on Windows by the "Print to File" option;
you will create a file with a name suffix of .prn; this appears to
be more or less standard postscript.