Java source code for
X52.9238
Definitions:
computer, program, project, package, file, class, method
A
computer
is a machine that follows instructions.
A
program
is a list of instructions for the computer to execute.
The instructions in a Java program must be divided into sections called
classes.
The first and last line of our first Java program,
HelloWorld.java,
mark the start and end of a class named
HelloWorld.
You will create this class in
step 4
of the HelloWorld Tutorial.
The instructions in a class must be further divided into subsections called
methods.
(In other languages, the methods are called
functions,
subroutines, or
procedures.)
The second and next-to-last lines of
HelloWorld.java
mark the start and end of a method named
main,
belonging to class
HelloWorld.
You will create this method in
step 4
when you check the checkbox for
public static void main.
The class
HelloWorld
will be written in a file named
HelloWorld.java,
also created in
step 4.
The set of files that make up a Java program
is called a
project.
Our project will be named
HelloWorld.
The project resides in a folder of the same name,
contained in the workspace folder which you created in
step 7
of the instructions for downloading Eclipse.
Our
HelloWorld
project will be very simple;
the only
.java
file that it will contain will be
HelloWorld.java.
(The project may contain other files,
but you dont have to look at them.)
You will create this project in
step 3.
A more complicated project might contain hundreds of
.java
files.
The files of a project are therefore divided into groups called
packages.
Our project will contain only one package, the default package,
which will contain only one
.java
file,
HelloWorld.java.
You will create this package in
step 4
when you leave the
Package:
box empty.
Download Java
On AWS:
sudo yum update
sudo yum install java
yum list installed 'java*'
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
Installed Packages
java-11-amazon-corretto.x86_64 1:11.0.6+10-1.amzn2 @amzn2-core
java-11-amazon-corretto-headless.x86_64 1:11.0.6+10-1.amzn2 @amzn2-core
javapackages-tools.noarch 3.4.1-11.amzn2 @amzn2-core
which javac
/usr/bin/javac
which java
/usr/bin/java
javac --version
javac 11.0.6
java --version
openjdk 11.0.6 2020-01-14 LTS
OpenJDK Runtime Environment Corretto-11.0.6.10.1 (build 11.0.6+10-LTS)
OpenJDK 64-Bit Server VM Corretto-11.0.6.10.1 (build 11.0.6+10-LTS, mixed mode)
On AWS, create a
bin
subdirectory of your home directory and create the following bash shellscript.
echo $PATH | tr : '\n' | cat -n
1 /usr/local/bin
2 /usr/bin
3 /usr/local/sbin
4 /usr/sbin
5 /home/user/.local/bin
6 /home/user/bin
cd
pwd
ls -l
mkdir bin
ls -l
drwxrwxr-x 2 user group 6 Jan 28 11:12 bin
chmod 755 bin
ls -l
drwxr-xr-x 2 user group 6 Jan 28 11:12 bin
cd bin
pwd
vi jav
chmod 755 jav
ls -l jav
vi MyProg.java
jav MyProg
ls -l MyProg.java MyProg.class
file MyProg.java
MyProg.java: C source, ASCII text
file MyProg.class
MyProg.class: compiled Java class data, version 55.0
#!/usr/bin/bash
#This bash shellscript is named jav.
#Put it in the bin subdirectory of your home directory.
#The first (or only) is the name of the .java file, without the .java extension.
if [[ $# -lt 1 ]]
then
echo $0: requires at least one command line argument 1>&2
exit 1
fi
if [[ ! -e $1.java ]]
then
echo $0: $1.java does not exist 1>&2
exit 1
fi
if [[ ! -f $1.java ]]
then
echo $0: $1.java must be a file 1>&2
exit 1
fi
if [[ ! -r $1.java ]]
then
echo $0: must have read permission for $1.java 1>&2
exit 1
fi
if ! javac $1.java
then
#Arrive here if javac $1.java did not produce exit status 0.
echo $0: $1.java did not compile 1>&2
exit 1
fi
java $* #$* is all the command line arguments passed to this shellscriprt.
#!/usr/bin/bash
#This shellscript is jget. Sample use: jget HelloWorld
if [[ $# -lt 1 ]]
then
echo $0: needs at least one argument 1>&2
exit 1
fi
cd ~/bin #The tilde stands for the name of the user's home directory.
if [[ -e $1.java ]]
then
echo -n "~/bin/$1.java already exists. Remove? [y/n]: "
read answer
if [[ $answer == 'y' ]] #string comparison, not numeric comparison
then
rm $1.java
else #anything other than y counts as no
exit 1
fi
fi
if ! wget -q http://oit2.scps.nyu.edu/~meretzkm/x52.9238/src/$1.java
then
echo $0: could not get http://oit2.scps.nyu.edu/~meretzkm/x52.9238/src/$1.java 1>&2
exit 1
fi
#Compile and run:
jav $*
Install Java on PC before Eclipse.
Download page.
• Accept License Agreement
jdk_13.0.2-windows_x64_bin.exe
Allow changes? Yes
Installs in
/C/Program Files/java/jdk-13.0.2
C:\Users\myname\eclipse-workspace
Printing
- HelloWorld.java:
System.out.println;
System.out
vs.
System.err.
- Dime1.java:
line separator:
println
vs.
print.
- Dime2.java
- Flag.java:
ASCII US flag.
Many lines of output.
Variables, operators, expressions
- Variable.java:
create, initialize, and print a variable.
- Expression.java:
operator precedence and associativity.
Math.abs.
- Remainder.java:
the
division
and
remainder
operators.
- Assign.java:
assign a new value to a variable;
final
variables;
i = i + 1;
- JobTake.java:
input,
division
and
remainder.
How long does the job take?
-
Input1.java:
input an integer by calling the method
java.util.Scanner.nextInt
and store the integer in a variable.
Blocking i/o.
-
Input2.java:
check for input failure with
java.util.Scanner.hasNextInt
.
-
Age.java, Wait.java, Cents.java, Turkey.java, Change.java
Control Structure
- NotToProgram.java
- While.java:
while
loop,
{curly braces},
(parentheses),
logical expression.
Digression:
System.out.printf
- 0 to 10 by 1s
- 0 to 20 by 1s
- 10 to 20 by 1s
- 10 to 20 by 2s: three vital statistics
- count down
- iterate zero times
- For1.java:
for
loop:
three vital statistics on same line, code is more localized.
- For2.java:
for
loop with local variable
- Beer.java: 100 Bottles of beer on the Wall
- Pierogies.java (parochial)
- Thruway.java
- Sum1.java:
sum the numbers from 1 to 10 (or to 100);
+=
- Sum2.java:
sum the numbers from 1 to
n.
- Sum3.java:
read
n
from the standard input.
- Sum4.java:
concatenate
Strings.
- Geometric.java:
geometric progression
- CountForever.java:
infinite for loop and
sleep
- Infinite.java:
infinite for loop with no induction variable at all
- DoWhile.java:
do-while
loop:
test at the bottom,
guessing game.
Nested Loops
- Nest.java:
nested for loops
(Lucy
in the Sky with Diamonds)
- Rectangle1.java:
rectangle hardwired for 4 rows and 5 columns.
Modify to make a triangle with 4 rows.
- Rectangle2.java:
rectangle with
nrows
rows and
ncols
columns
- Graph1.java:
graph paper with one loop
(hardwired for 10 rows and 10 columns)
- Graph2.java:
graph paper with nested for loops
(hardwired for 10 rows and 10 columns)
- Graph3.java:
graph paper with nested for loops
(nrows
rows and
ncols
columns)
- If.java:
if
without else.
- Else1.java
and
Else2.java:
a pair of consecutive, mutually exclusive
if
statements;
the else keyword
- UpsideDown.java:
put the smaller clause at the top.
- IsPrime.java:
if inside of for loop;
System.exit
- Primes.java:
labelled
continue.
Skip this.
- IfInThen1.java
and
IfInThen2.java:
if inside of then (profit vs. loss).
Last test is sometimes unnecessary.
- IfInElse1.java
and
IfInElse2.java:
if inside of else.
Last test is sometimes unnecessary.
- ElseIf1.java
and
ElseIf2.java:
an else occupied entirely by an if.
- TooLow.java:
the
DoWhile.java
guessing game with hints.
java.util.Random.nextInt
- ThreeWay.java:
making, losing, breaking even.
The Metro-North evacuation instructions:
- Remain inside the train if possible.
If not …
- Go to next car through end doors.
If Unable …
- Open side door and get out.
If you cant …
- Go out emergency windows.
- FourWayLeap.java:
leap year
- FourWayOrdinal.java:
the expression
i % 100
is the two rightmost digits of
i
.
if (11 <= i % 100 && i % 100 <= 13) {
System.out.println("th");
} else if (i % 10 == 1) {
System.out.println("st");
} else if (i % 10 == 2) {
System.out.println("nd");
} else if (i % 10 == 3) {
System.out.println("rd");
} else {
System.out.println("th");
}
- Switch1.java
and
Switch2.java:
presidential/congressional/local election year
switch
statement with breaks.
NoBreaks.java:
why the
switch
statement needs the breaks.
See also
Christmas1.java.
-
Exercise (don’t peek).
Christmas1.java
and
Christmas2.java
(with array and the ternary operator)
print
The Twelve Days of Christmas.
Data types
- Int.java:
division truncates; wrap around.
- Integers.java.
The
integral
types
(except char):
byte, short, int, long.
Farther in the negative direction.
byte: –128 to 127
short: –32,768 to 32,767
int: –2,147,483,648 to 2,147,483,647
long: –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
- DemoBigInteger.java:
class
BigInteger;
also
BigDecimal.
- Floating.java:
float, double
- Interest.java:
how many years does it take for the principal to double?
double variables,
do-while loop,
natural logarithm
Math.log
- Organ.java:
organ pipes spanning one octave.
double variables,
for loop,
Math.pow
- Pi.java:
compute π by the Monte Carlo method.
- Solve.java
- Char.java
and cast to int.
Unicode
character code charts:
Russian,
Arabic,
etc.
- DemoString.java:
class
String
- DemoBool.java:
boolean
- Array1.java
and
Array2.java:
create an array of
ints (month lengths) and an array of Strings (month name)
- YearOfThe.java:
array of
Strings
- Plot.java:
a
movie plot generator
with three
arrays of
Strings.
- Dependents1.java
and
Dependents2.java:
number of dependents, without and with an array.BubbleSort.java
and
BubbleSortStrings.java
an array of
ints
and
Strings.
String.compareTo
and
String.compareToIgnoreCase
- Beethoven1.java
and
Beethoven2.java:
play the
Ode to Joy.
Synthesizer,
MidiChannel.
start → Settings → Control Panel → Sound → volume up.
- Manhattan.java:
find the street number along an avenue.
Street1.java,
Street2.java,
Street3.java:
the advantage of using an array.
Compare
YearOfThe.java,
with and without an array.
- MyRandom.java:
create an array with new.
- TwoD.java:
two-dimensional array:
tic-tac-toe board
- DetectWin.java:
detect win at tic-tac-toe.
- MakeWin.java:
make the winning move at tic-tac-toe.
Three-dimensional array.
- SpreadSheet.java:
spreadsheet of doubles
- Parallel.java:
two-dimensional array holds parallel columns of integers:
pitch and length
Static
methods
(i.e., methods that do not belong to objects)
|
In fact the manager said
afterwards that Mr. Kurtzs methods had ruined the district.
| |
—Joseph Conrad (1857–1924),
Heart
of Darkness
(1899)
|
A
static method
is a method that does not belong to any object.
We have already seen examples:
Math.sqrt,
System.exit.
Math and System are not objects.
A static method does belong to a class, however.
Math and System are classes.
- Method1.java
and
Method2.java:
Secret
Agent Man.
We already wrote a method (sleep)
in
Beer.java.
- MyPrint.java:
pass a non-array argument to a method
- ArrayArg.java:
pass an array argument to a method.
Pass an array of
Stringss
to
main.
- ReturnValue.java:
return a value from a method.
Print an error message with
System.err.println
if the argument is illegal.
(We already returned a value from the
Input.getInt
method in
Input.java.)
Static fields
(i.e., fields that do not belong to objects)
Until now, every variable was declared inside the body of a method.
A
static field
is a variable declared outside the body of a method.
Although it belongs to no method,
a static field does belong to a class.
The last example is new.
- Integers.java:
Class
Integer
has the static fields
Integer.MIN_VALUE
and
Integer.MAX_VALUE.
- Pi.java:
Class
Math
has the static field
Math.PI.
- Input.java:
Class
Input
has the static field
Input.reader.
- Beethoven1.java:
Class
Beethoven1
has the static fields
Beethoven1.synthesizer,
Beethoven1.channel,
Beethoven1.C,
Beethoven1.D,
Beethoven1.E,
etc.
- Total.java:
new example of a static field
Total.total.
Objects with fields
- Field.java:
object with two fields and a
toString
member function.
Fields initialized to default values.
Motivated by parallel arrays in
Array2.java.
- Constructor.java:
fields initialized by constructor.
-
ArrayOfObjects1.java
and
ArrayOfObjects2.java
array of objects.
-
ArrayOfObjects3.java:
mass produce an array of objects using a
for
loop.
-
Retrofit a single array of objects into all of our parallel array examples:
Array2.java.
Beethoven2.java
with parallel arrays of pitch, volume, duration.
Objects with methods
- DateDemo.java:
fields are private, methods are public.
- CarDemo.java:
has a
siphon
method that accesses two
Car
objects.
Math.min.
- PointDemo.java:
a point in a two-dimensional space.
Extend a base class
- CricketDemo.java:
class
MetricCricket
(the subclass)
extends
class
Cricket
(the superclass).
The constructor for the subclass calls the constructor for the superclass.
- AmnioteDemo.java
add new fields instead of new methods.
- Car2Demo.java:
class
Car2
(the subclass)
extends
class
Car
(the superclass).
The constructor for the subclass calls the constructor for the superclass.
- Date2Demo.java:
a class with a missing piece is an abstract class.
Implement an
interface
that handles an event
-
Inter.java
-
Go to
Android,
scroll down to "Controls and Listeners",
click on the first example,
Click Listener.
In the Android example,
the interface
View.OnClickListener
plays the rôle of the interface
Point
,
and the class
MyOnClickListener
plays the rôle of class
CartesianPoint
.
- Bug.java:
classes
Display
and
Shell,
GC
and
Color.
PaintListener
is merely an
interface:
a class with a missing method.
In this case, the missing method is
paintControl,
which we had to write ourselves.
Similarly,
KeyListener
is also an interface:
we have to write the missing methods
keyPressed
and
keyReleased.
(Class
KeyAdapter
has no missing pieces, but its
keyPressed
and
keyReleased
methods do nothing.)
The argument of
paintControl
must be a
PaintEvent
object, which has a field of class
GC,
which has the method
fillRectangle.
The argument of
keyPressed
and
keyReleased
must be a
KeyEvent
object.
https://download.eclipse.org/eclipse/downloads/drops4/R-4.14-201912100610/#SWT
- MouseBug.java:
a
MouseListener
as well as a
KeyListener.
Throw and catch an exception
-
Throw1.java:
int division by zero throws a
java.lang.ArithmeticException
.
double division doesn’t.
-
Throw2.java
- TryThrowCatchFinally1.java:
throw an exception and catch it in the same method.
The keywords
try,
throw,
catch,
and
finally.
- TryThrowCatchFinally2.java:
Throw the exception in one method,
catch it in another method.
The
throws
keyword.
- CountForever.java:
Thread.sleep
will throw the
InterruptedException
if it is interrupted by the
Thread.interrupt
method.
- Input.java:
BufferedReader.readLine
throws
IOException
if an I/O error occurs;
Integer.parseInt
throws
NumberFormatException
if the characters that were read in do not spell an integer value.
- Beethoven1.java:
catch MidiUnavailableException.
Input and output
These four abstract classes have abstract
read
and
write
methods for
bytes
and chars.
Classes
PrintStream
(8-bit)
and
PrintWriter
(16-bit)
have
println
methods as well as
write
methods.
These classes are derived from
OutputStream
and
Writer
respectively.
For example,
System.out
and
System.err
are
PrintStreams.
System.in
is an
InputStream.
To read the values that were written by a
PrintStream
or
Writer,
put a
Scanner
object
on top of an
InputStream
or
Reader.
byte output
- HelloWorld.java.
A
PrintStream
outputs bytes that represent characters, numbers, etc.
- FormatDemo.java.
The first argument of
PrintStream.format
is a
format string.
The method throws
IllegalFormatException
and
NullPointerException.
byte input
- InputStreamDemo1.java.
System.in
is an
InputStream,
which reads bytes, not characters.
The
read
method of
PrintStream
reads one byte and returns an int giving the value of that byte
(0–255 inclusive).
Character.isISOControl.
- InputStreamDemo2.java.
Read digits that spell out an integer value.
Character.isDigit
and
Character.getNumericValue.
- ScannerDemo1.java:
Scanner.nextInt,
Scanner.nextDouble,
Scanner.next.
Detect failure by catching exceptions.
- ScannerDemo2.java:
Scanner.hasNextInt,
hasNextDouble,
hasNext.
Detect failure with
if
statements.
A digression on 16-bit char input
- InputStreamReaderDemo.java.
With an
InputStream,
you can read bytes 0–255 inclusive).
If you also have an
an
InputStreamReader,
you can read bytes and get chars (0–65535 inclusive).
- BufferedReaderDemo.java.
The above classes
InputStream
and
InputStreamReader
let you read one byte or char at a time.
They will also let you read an array of bytes or chars,
but you have to know in advance
exactly how many bytes or chars you want to read.
A
BufferedReader
will let you read up to and including the next '\n', '\r', or '\r\n'.
- Input.java.
Call the static method
Integer.ParseInt
instead of constructing a
Scanner
object.
byte file output and byte file input
- FileOutputStreamDemo.java.
A
FileOutputStream
writes bytes to a file.
Easier to use if you put a
PrintStream
on top of it.
(System.out
is an example of a
PrintStream.
This class has the
println method.)
- FileInputStreamDemo.java.
A
FileInputStream
reads bytes from a file.
Easier to use if you put a
Scanner
on top of it.
- RandomAccessFileDemo.java.
A
RandomAccessFile
has a
seek
method.
- FileDemo.java:
A
File
object tells you information about a file on the disk,
starting with whether the file exists.
Class
Date.
TCP/IP socket i/o
A conversation between a server and a client is always initiated by the client.
In other words, the client talks first.
On the other hand, the server is usually launched first.
It is usually running long before the client talks to it,
and continues running after the conversation is finished.
In fact, a server usually converses with many clients simultaneously.
- Client.java:
Use class
java.net.Socket
for TCP/IP, class
java.net.DatagramSocket
for UDP/IP.
The 16-bit port number (13) identifies which server program the client
wants to talk to on the remote host.
Port 80 is the web server.
See
/etc/services
for a list of other port numbers.
The awk wildcard in square brackets contains one space and one tab.
sed 's/#.*//' /etc/services | awk '$2 ~ /^80[^0-9]/'
http 80/tcp www www-http # WorldWideWeb HTTP
http 80/udp www www-http # HyperText Transfer Protocol
http 80/sctp # HyperText Transfer Protocol
netstat -at
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 localhost:smtp 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:sunrpc 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:ssh 0.0.0.0:* LISTEN
tcp 0 1281 ip-172-31-85-59.ec2:ssh 222.186.52.139:45546 FIN_WAIT1
tcp 0 264 ip-172-31-85-59.ec2:ssh oit2.scps.nyu.edu:51828 ESTABLISHED
tcp6 0 0 [::]:sunrpc [::]:* LISTEN
tcp6 0 0 [::]:54321 [::]:* LISTEN
tcp6 0 0 [::]:ssh [::]:* LISTEN
tcp6 0 0 localhost:54321 localhost:51762 TIME_WAIT
tcp6 0 0 localhost:54321 localhost:51760 TIME_WAIT
netstat -at | awk 'NR <= 2 || $4 ~ /:54321$/'
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp6 0 0 [::]:54321 [::]:* LISTEN
-
Server1.java.
This server serves exactly one client and then dies.
The service it renders is to send the word "Hello".
Class
ServerSocket
.
Change client to
Socket socket = new Socket("localhost", 54321);
-
ThreadDemo.java:
do two or more things a the same time.
Class
Thread.
-
Server2.java.
A multi-threaded server that serves many clients simultaneously.
SWT
Programs
- HelloWorldSWT.java:
open and close an SWT window.
Classes
Display
and
Shell.
- FillRectangle.java:
fill a rectangle in a window.
PaintListener
is merely an interface: a class with a missing method.
In this case, the missing method is
paintControl;
we had to write it ourselves.
Similarly,
KeyListener
is also an interface:
we have to write the missing methods
keyPressed
and
keyReleased.
The argument of
paintControl
must be a
PaintEvent
object, which has a field of class
GC,
which has the method
fillRectangle.
- For1SWT.java:
fill a column of squares with a
for
loop.
- For2SWT.java:
fill rows and columns of squares with nested
for
loops.
- FlagSWT.java
and
DominicanSWT.java:
nested for loops, else-if.
- Rose.java
- Sudoku.java
start → Settings → Control Panel → Sound → volume up.
- Beethoven1.java
and
- Beethoven2.java:
play the
Ode to Joy
Windowing packages:
AWT,
SWT,
Swing
- Window1AWT.java:
packages
java.awt
and
java.awt.event.
- Window2AWT.java
with an anonymous
inner
class
- WindowSWT.java:
package
org.eclispe.swt.widgets.
As in
HelloWorldSWT.java,
remember to say
Properties
→ Java Build Path
→ Projects
→ Add…
→ org.eclipse.swt
- WindowSwing.java:
package
javax.swing
CSV format: comma-separated values
-
CSV1.java
inputs the CSV file
yob2018.txt
.
Class
java.util.Scanner
,
method
split
.
The interface
java.util.List
is implemented by the class
java.util.ArrayList
.
This example is inspired by my
pandas
course.
#!/usr/bin/bash
#This shellscript is named tester (not test).
#Compile and run CSV1.java.
cd ~/bin
if ! javac CSV1.java
then
exit 1
fi
wget -q -O - http://oit2.scps.nyu.edu/~meretzkm/pandas/teaser/yob2018.txt |
java CSV1 |
head -10
exit 0
Count the number of male births in America in 2019.
Don’t make the fields of class
Name
private.
To make the code clearer,
add two static fields to class
CSV1
.
private static final boolean M = true;
private static final boolean F = false;
Change the last
for
loop to
int boys = 0;
for (Name name: list) {
if (name.sex == M) {
boys += name.births;
}
}
System.out.println(boys);
Recursion
-
RecursivePrint1.java.
-
RecursivePrint2.java.
-
Factorial.java.
-
Factorial.java.
-
TreePrint1.java.
-
TreePrint2.java.
-
KthLargest.java.
Given a sorted binary tree,
find the node with the kth largest value.
-
QuickSort1.java.
Sort an
ArrayList<Integer>
.
Easier to read in
Python.
-
QuickSort2.java:
create the three shorter
List
s
using lambdas.
//Could have created smallValues in five separate statements:
//See package java.util.stream
Stream<Integer> streamOfIntegers = list.stream();
Predicate<Integer> predicate = i -> i < pivot;
Stream<Integer> shorterStream = streamOfIntegers.filter(predicate);
Collector<Integer, ?, List<Integer>> collector = Collectors.toList();
var smallValues = shorterStream.collect(collector);
-
Maze.java
and a
Python
version.
Make it non-static.
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXX.XXXXXXXX+++++++BX
XA+XXX........X+XXXXXXXX
XX+XXX.XXXXXXXX+XXX.XXXX
XX+++++++XX+++++....XXXX
XXXXXXXX+XX+XXX.XXX.XXXX
XXXX.XXX+XX+XXX.XXX.XXXX
XXXX....++++...XXXX.XXXX
XXXXXXXXXXXXXXXXXX..XXXX
XXXXXXXXXXXXXXXXXXXXXXXX
-
Dijkstra.java:
Dijkstra’s
Algorithm.
XX XX XX XX XX XX XX
XX 00 01 02 03 04 XX
XX 01 XX 03 XX XX XX
XX 02 03 04 XX 99 XX
XX XX XX XX XX XX XX
XX XX XX XX XX XX XX
XX 00 01 02 03 04 XX
XX 01 XX 03 XX XX XX
XX 02 03 04 XX 99 XX
XX XX XX XX XX XX XX
#!/usr/bin/bash
#This shellscript is colorize.
#NF is the number of fields on each line.
awk '{
for (i = 1; i <= NF; ++i) {
if ($i != "XX") {
n = int($i)
if (n == 99) {
bg = "black" #inaccessible
} else {
n = 255 - 20 * n
bg = sprintf("#%02X%02X%02X", n, n, n)
}
$i = "<SPAN STYLE = \"background-color: " bg ";\">" $i "</SPAN>"
}
}
print
}'
exit 0
$ jav Dijkstra | colorize
Lambdas
-
Lambda.java: the simplest example I could find.
Things to do differently next time
Use the simpler
getInt
method in
Input.java.
Do exceptions earlier, as part of control structure.
Do SWT drawing and sound
after
exceptions.
Add 16-bit char file i/o.
AWT, SWT, Swing: trio of simpler example, without objects and redrawing.
Keep the focus on loops, if statements, arrays.
Outstanding programming projects
-
Write
The Twelve Days of Christmas.
-
Research project:
create an array of objects where the constructor for each object
takes two arguments of different types (e.g.,
String
and
int
as in
ArrayOfObjects1.java,
ArrayOfObjects2.java,
ArrayOfObjects3.java.
-
In
DateDemo.java,
add non-static methods
prev
and
compareTo
to class
MyDate
.
Add static method
numberOfDays
to class
MyDate
.
Should
compareTo
be static?
-
In
CarDemo.java,
make
siphon
static.
siphon
should still receive references to two objects of class
Car
.
-
In
PointDemo.java,
change
x
and
y
from
double
to
int
.
A
Point
object now represents the coördinates of a pixel on a screen.
Add two static int fields named
width
and
height
to class
Point
,
giving the dimensions of the screen.
The constructor for class
Point
should use these static fields to make sure the numbers are within
the legal ranges.
Maybe you could also give class
Point
a nonstatic method named
move
that would change the
Point
’s
x
and
y
.
This method should also do error checking.
-
In
Date2Demo.java,
remove class
Date
.
Write classes
FastDate
and
SmallDate
without using inheritance.