();
13 |
14 | public void clear() {
15 | synchronized(taskList) {
16 | taskList.clear();
17 | }
18 | }
19 |
20 | public void add(Runnable task) {
21 | synchronized(taskList) {
22 | taskList.addLast(task);
23 | taskList.notify();
24 | }
25 | }
26 |
27 | public Runnable take() throws InterruptedException {
28 | synchronized(taskList) {
29 | while (taskList.isEmpty())
30 | taskList.wait();
31 | return taskList.removeFirst();
32 | }
33 | }
34 |
35 | } // end MyLinkedBlockingQueue
36 |
--------------------------------------------------------------------------------
/javanotes9/src-c12/netgame/chat/ChatRoomServer.java:
--------------------------------------------------------------------------------
1 | package netgame.chat;
2 |
3 | import java.io.IOException;
4 | import netgame.common.Hub;
5 |
6 | /**
7 | * This class contains just a small main class that creates a Hub
8 | * and starts it listening on port 37829. This port is used
9 | * by the ChatRoomWindow application. This program should be run
10 | * on the computer that "hosts" the chat room. See the ChatRoomWindow
11 | * class for more details. Once the server starts listening, it
12 | * will listen for connection requests from clients until the
13 | * ChatRoomServer program is terminated (for example by a
14 | * Control-C).
15 | * Note that the ChatRoom application uses a basic, generic
16 | * Hub, which simply forwards any message that it receives from
17 | * a client to all connected clients (including the one that
18 | * sent it), wrapped in an object of type ForwardedMessage.
19 | */
20 | public class ChatRoomServer {
21 |
22 | private final static int PORT = 37829;
23 |
24 | public static void main(String[] args) {
25 | try {
26 | new Hub(PORT);
27 | }
28 | catch (IOException e) {
29 | System.out.println("Can't create listening socket. Shutting down.");
30 | }
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/javanotes9/src-c12/netgame/common/DisconnectMessage.java:
--------------------------------------------------------------------------------
1 | package netgame.common;
2 |
3 | import java.io.Serializable;
4 |
5 | /**
6 | * A DisconnectMesaage is sent from a Client to the Hub when that
7 | * client wants to disconnect. A DisconnectMessage is also sent from
8 | * the Hub to each client just before it shuts down normally. DisconnectMessages
9 | * are for internal use in the netgame.common package and are not used
10 | * directly by users of the package.
11 | */
12 | final class DisconnectMessage implements Serializable {
13 |
14 | /**
15 | * The message associated with the disconnect. When the Hub
16 | * sends disconnects because it is shutting down, the message
17 | * is "*shutdown*".
18 | */
19 | final public String message;
20 |
21 | /**
22 | * Creates a DisconnectMessage containing a given String, which
23 | * is meant to describe the reason for the disconnection.
24 | */
25 | public DisconnectMessage(String message) {
26 | this.message = message;
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/javanotes9/src-c12/netgame/common/ForwardedMessage.java:
--------------------------------------------------------------------------------
1 | package netgame.common;
2 |
3 | import java.io.Serializable;
4 |
5 | /**
6 | * Represents a message that was received by the Hub from
7 | * one clients and that is being forwarded to all clients.
8 | * A ForwardedMessage includes the message that was sent
9 | * by a client to the Hub and the ID number of the client
10 | * who sent it. The default action of a Hub -- defined
11 | * in the messageReceived(playerID,message) method of
12 | * that class -- is to wrap the message in a ForwardedMessage
13 | * and send the ForwardedMessage to all connected client,
14 | * including the client who sent the original message.
15 | * When an application uses a subclass of Hub, it is
16 | * likely to override that behavior.
17 | */
18 | public class ForwardedMessage implements Serializable {
19 |
20 | public final Object message; // Original message from a client.
21 | public final int senderID; // The ID of the client who sent that message.
22 |
23 | /**
24 | * Create a ForwadedMessage to wrap a message sent by a client.
25 | * @param senderID the ID number of the original sender.
26 | * @param message the original message.
27 | */
28 | public ForwardedMessage(int senderID, Object message) {
29 | this.senderID = senderID;
30 | this.message = message;
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/javanotes9/src-c12/netgame/common/ResetSignal.java:
--------------------------------------------------------------------------------
1 | package netgame.common;
2 |
3 | /**
4 | * This package private class is used internally in Hub and Client
5 | * to send a signal to the message output thread that the output
6 | * stream should be reset. A ResetSignal has no data.
7 | */
8 | class ResetSignal {
9 | }
10 |
--------------------------------------------------------------------------------
/javanotes9/src-c12/netgame/common/StatusMessage.java:
--------------------------------------------------------------------------------
1 | package netgame.common;
2 |
3 | import java.io.Serializable;
4 |
5 | /**
6 | * The Hub sends a StatusMessage to all connected clients when
7 | * a player connects or disconnects. When a player connects,
8 | * that player receives the status message caused by their
9 | * connecting. When a player disconnects, that player does
10 | * not receive a copy of the status message that is sent.
11 | * StatusMessages are from internal use in the netgame.common
12 | * package and users of this package do not have to deal with
13 | * them. This package private class is only used internally
14 | * in the netgame.common package. Users of the package will
15 | * not see these messages; instead, the Client's playerConnected()
16 | * or playerDisconnected() method will be called.
17 | */
18 | final class StatusMessage implements Serializable {
19 |
20 | /**
21 | * The ID number of the player who has connected or disconnected.
22 | */
23 | public final int playerID;
24 |
25 | /**
26 | * True if the player has just connected; false if the player
27 | * has just disconnected.
28 | */
29 | public final boolean connecting;
30 |
31 | /**
32 | * The list of players after the change has been made.
33 | */
34 | public final int[] players;
35 |
36 | public StatusMessage(int playerID, boolean connecting, int[] players) {
37 | this.playerID = playerID;
38 | this.connecting = connecting;
39 | this.players = players;
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/javanotes9/src-c12/netgame/fivecarddraw/cards.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c12/netgame/fivecarddraw/cards.png
--------------------------------------------------------------------------------
/javanotes9/src-c13/StopWatchLabel.java:
--------------------------------------------------------------------------------
1 |
2 | import javafx.scene.control.Label;
3 |
4 | /**
5 | * A custom component that acts as a simple stop-watch. When the user clicks
6 | * on it, this component starts timing. When the user clicks again,
7 | * it displays the time between the two clicks. Clicking a third time
8 | * starts another timer, etc. While it is timing, the label just
9 | * displays the message "Timing....".
10 | */
11 | public class StopWatchLabel extends Label {
12 |
13 | private long startTime; // Start time of timer.
14 | // (Time is measured in milliseconds.)
15 |
16 | private boolean running; // True when the timer is running.
17 |
18 | /**
19 | * Constructor sets initial text on the label to
20 | * "Click to start timer." and sets up a mouse event
21 | * handler so the label can respond to clicks.
22 | */
23 | public StopWatchLabel() {
24 | super(" Click to start timer. ");
25 | setOnMousePressed( e -> setRunning( !running ) );
26 | }
27 |
28 |
29 | /**
30 | * Tells whether the timer is currently running.
31 | */
32 | public boolean isRunning() {
33 | return running;
34 | }
35 |
36 |
37 | /**
38 | * Sets the timer to be running or stopped, and changes the text that
39 | * is shown on the label. (This method should be called on the JavaFX
40 | * application thread.)
41 | * @param running says whether the timer should be running; if this
42 | * is equal to the current state, nothing is done.
43 | */
44 | public void setRunning( boolean running ) {
45 | if (this.running == running)
46 | return;
47 | this.running = running;
48 | if (running == true) {
49 | // Record the time and start the timer.
50 | startTime = System.currentTimeMillis();
51 | setText("Timing....");
52 | }
53 | else {
54 | // Stop the timer. Compute the elapsed time since the
55 | // timer was started and display it.
56 | long endTime = System.currentTimeMillis();
57 | double seconds = (endTime - startTime) / 1000.0;
58 | setText( String.format("Time: %1.3f seconds", seconds) );
59 | }
60 | }
61 |
62 | } // end StopWatchLabel
63 |
--------------------------------------------------------------------------------
/javanotes9/src-c13/TestStopWatch.java:
--------------------------------------------------------------------------------
1 |
2 | import javafx.application.Application;
3 | import javafx.scene.Scene;
4 | import javafx.stage.Stage;
5 | import javafx.scene.layout.StackPane;
6 | import javafx.geometry.Pos;
7 |
8 | /**
9 | * Shows a StopWatchLabel. The user can click to start a timer
10 | * and click again to stop it. The elapsed time is displayed.
11 | */
12 | public class TestStopWatch extends Application {
13 |
14 | public static void main(String[] args) {
15 | launch(args);
16 | }
17 | //------------------------------------------------------------
18 |
19 | public void start(Stage stage) {
20 |
21 | StopWatchLabel stopWatch = new StopWatchLabel();
22 | stopWatch.setStyle("-fx-font: bold 30pt serif; -fx-background-color:#ffffee;"
23 | + "-fx-border-color:#008; -fx-border-width:3px; -fx-padding:20px;"
24 | + "-fx-text-fill: #008");
25 | stopWatch.setMaxSize(Double.POSITIVE_INFINITY,Double.POSITIVE_INFINITY);
26 | stopWatch.setAlignment(Pos.CENTER);
27 |
28 | stage.setScene( new Scene(new StackPane(stopWatch)) );
29 | stage.setTitle("StopWatchLabel Demo");
30 | stage.show();
31 |
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/javanotes9/src-c13/cards.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/cards.png
--------------------------------------------------------------------------------
/javanotes9/src-c13/edu/hws/eck/mdbfx/examples/README.txt:
--------------------------------------------------------------------------------
1 |
2 | The files in this "examples" directory are used in the applet
3 | version of the Mandelbrot Viewer program , which is defined in
4 | the file MandelbrotApplet.java. They are NOT needed by any
5 | other part of the program.
6 |
7 | Note that these are "Params" files that can also be loaded by
8 | hand into the stand-alone application version of the program
9 | using its Open Params command.
10 |
11 |
--------------------------------------------------------------------------------
/javanotes9/src-c13/edu/hws/eck/mdbfx/examples/settings1.mdb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/javanotes9/src-c13/edu/hws/eck/mdbfx/examples/settings10.mdb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/javanotes9/src-c13/edu/hws/eck/mdbfx/examples/settings11.mdb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/javanotes9/src-c13/edu/hws/eck/mdbfx/examples/settings12.mdb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/javanotes9/src-c13/edu/hws/eck/mdbfx/examples/settings2.mdb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/javanotes9/src-c13/edu/hws/eck/mdbfx/examples/settings3.mdb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/javanotes9/src-c13/edu/hws/eck/mdbfx/examples/settings4.mdb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/javanotes9/src-c13/edu/hws/eck/mdbfx/examples/settings5.mdb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/javanotes9/src-c13/edu/hws/eck/mdbfx/examples/settings6.mdb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/javanotes9/src-c13/edu/hws/eck/mdbfx/examples/settings7.mdb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/javanotes9/src-c13/edu/hws/eck/mdbfx/examples/settings8.mdb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/javanotes9/src-c13/edu/hws/eck/mdbfx/examples/settings9.mdb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/javanotes9/src-c13/face-smile.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/face-smile.png
--------------------------------------------------------------------------------
/javanotes9/src-c13/nature-images/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/nature-images/.DS_Store
--------------------------------------------------------------------------------
/javanotes9/src-c13/nature-images/README.txt:
--------------------------------------------------------------------------------
1 | The files in this directory are public domain
2 | images downloaed from WikiMedia.
3 |
--------------------------------------------------------------------------------
/javanotes9/src-c13/nature-images/bluejay.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/nature-images/bluejay.jpg
--------------------------------------------------------------------------------
/javanotes9/src-c13/nature-images/chipmunk.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/nature-images/chipmunk.jpg
--------------------------------------------------------------------------------
/javanotes9/src-c13/nature-images/collie.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/nature-images/collie.jpg
--------------------------------------------------------------------------------
/javanotes9/src-c13/nature-images/elephants.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/nature-images/elephants.jpg
--------------------------------------------------------------------------------
/javanotes9/src-c13/nature-images/faun.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/nature-images/faun.jpg
--------------------------------------------------------------------------------
/javanotes9/src-c13/nature-images/lion.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/nature-images/lion.jpg
--------------------------------------------------------------------------------
/javanotes9/src-c13/nature-images/polar-bear.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/nature-images/polar-bear.jpg
--------------------------------------------------------------------------------
/javanotes9/src-c13/nature-images/stork.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/nature-images/stork.jpg
--------------------------------------------------------------------------------
/javanotes9/src-c13/stamper_icons/README.txt:
--------------------------------------------------------------------------------
1 | The icons in this folder are for the sample program
2 | SillyStamper.java. They were taken from the KDE desktop
3 | icon collection.
4 |
5 |
--------------------------------------------------------------------------------
/javanotes9/src-c13/stamper_icons/icon10.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/stamper_icons/icon10.png
--------------------------------------------------------------------------------
/javanotes9/src-c13/stamper_icons/icon11.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/stamper_icons/icon11.png
--------------------------------------------------------------------------------
/javanotes9/src-c13/stamper_icons/icon24.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/stamper_icons/icon24.png
--------------------------------------------------------------------------------
/javanotes9/src-c13/stamper_icons/icon25.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/stamper_icons/icon25.png
--------------------------------------------------------------------------------
/javanotes9/src-c13/stamper_icons/icon26.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/stamper_icons/icon26.png
--------------------------------------------------------------------------------
/javanotes9/src-c13/stamper_icons/icon31.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/stamper_icons/icon31.png
--------------------------------------------------------------------------------
/javanotes9/src-c13/stamper_icons/icon33.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/stamper_icons/icon33.png
--------------------------------------------------------------------------------
/javanotes9/src-c13/stamper_icons/icon34.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/stamper_icons/icon34.png
--------------------------------------------------------------------------------
/javanotes9/src-c13/stamper_icons/icon5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/stamper_icons/icon5.png
--------------------------------------------------------------------------------
/javanotes9/src-c13/stamper_icons/icon7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/stamper_icons/icon7.png
--------------------------------------------------------------------------------
/javanotes9/src-c13/stamper_icons/icon8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/stamper_icons/icon8.png
--------------------------------------------------------------------------------
/javanotes9/src-c13/stamper_icons/icon9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/stamper_icons/icon9.png
--------------------------------------------------------------------------------
/javanotes9/src-c13/tile.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c13/tile.png
--------------------------------------------------------------------------------
/javanotes9/src-c2/CreateProfile.java:
--------------------------------------------------------------------------------
1 | import textio.TextIO;
2 |
3 | /**
4 | * Creates a file named "profile.txt" containing four lines of information
5 | * about the user. The user is prompted to enter the required information.
6 | *
7 | */
8 | public class CreateProfile {
9 |
10 | public static void main(String[] args) {
11 |
12 | String name; // The user's name.
13 | String email; // The user's email address.
14 | double salary; // the user's yearly salary.
15 | String favColor; // The user's favorite color.
16 |
17 | TextIO.putln("Good Afternoon! This program will create");
18 | TextIO.putln("your profile file, if you will just answer");
19 | TextIO.putln("a few simple questions.");
20 | TextIO.putln();
21 |
22 | /* Gather responses from the user. */
23 |
24 | TextIO.put("What is your name? ");
25 | name = TextIO.getln();
26 | TextIO.put("What is your email address? ");
27 | email = TextIO.getln();
28 | TextIO.put("What is your yearly income? ");
29 | salary = TextIO.getlnDouble();
30 | TextIO.put("What is your favorite color? ");
31 | favColor = TextIO.getln();
32 |
33 | /* Write the user's information to the file named profile.txt. */
34 |
35 | TextIO.writeFile("profile.txt"); // subsequent output goes to file
36 | TextIO.putln("Name: " + name);
37 | TextIO.putln("Email: " + email);
38 | TextIO.putln("Favorite Color: " + favColor);
39 | TextIO.putf( "Yearly Income: $%,1.2f%n", salary);
40 |
41 | /* Print a final message to standard output. */
42 |
43 | TextIO.writeStandardOutput();
44 | TextIO.putln("Thank you. Your profile has been written to profile.txt.");
45 |
46 | }
47 |
48 | }
--------------------------------------------------------------------------------
/javanotes9/src-c2/Day.java:
--------------------------------------------------------------------------------
1 | /**
2 | * This file defines an enum representing the days of the week.
3 | */
4 | public enum Day {
5 | SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
6 | }
7 |
--------------------------------------------------------------------------------
/javanotes9/src-c2/EnumDemo.java:
--------------------------------------------------------------------------------
1 | /**
2 | * This program demonstrates the use of enum types.
3 | * The enum types Day and Month are defined in this file.
4 | */
5 | public class EnumDemo {
6 |
7 | // Define two enum types. (In Java 17, these definitions could also be
8 | // inside main(), but earlier versions of Java require them to be outside
9 | // main(), or in a separate .java file.)
10 |
11 | enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
12 |
13 | enum Month { JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC }
14 |
15 | public static void main(String[] args) {
16 |
17 | Day tgif; // Declare a variable of type Day.
18 | Month libra; // Declare a variable of type Month.
19 |
20 | tgif = Day.FRIDAY; // Assign a value of type Day to tgif.
21 | libra = Month.OCT; // Assign a value of type Month to libra.
22 |
23 | System.out.print("My sign is libra, since I was born in ");
24 | System.out.println(libra); // Output value will be: OCT
25 | System.out.print("That's the ");
26 | System.out.print( libra.ordinal() );
27 | System.out.println("-th month of the year.");
28 | System.out.println(" (Counting from 0, of course!)");
29 |
30 | System.out.print("Isn't it nice to get to ");
31 | System.out.println(tgif); // Output value will be: FRIDAY
32 |
33 | System.out.println( tgif + " is the " + tgif.ordinal()
34 | + "-th day of the week.");
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/javanotes9/src-c2/HelloWorld.java:
--------------------------------------------------------------------------------
1 | /** A program to display the message
2 | * "Hello World!" on standard output.
3 | */
4 | public class HelloWorld {
5 |
6 | public static void main(String[] args) {
7 | System.out.println("Hello World!");
8 | }
9 |
10 | } // end of class HelloWorld
11 |
--------------------------------------------------------------------------------
/javanotes9/src-c2/Interest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * This class implements a simple program that
3 | * will compute the amount of interest that is
4 | * earned on $17,000 invested at an interest
5 | * rate of 0.027 for one year. The interest and
6 | * the value of the investment after one year are
7 | * printed to standard output.
8 | */
9 | public class Interest {
10 |
11 | public static void main(String[] args) {
12 |
13 | /* Declare the variables. */
14 |
15 | double principal; // The value of the investment.
16 | double rate; // The annual interest rate.
17 | double interest; // Interest earned in one year.
18 |
19 | /* Do the computations. */
20 |
21 | principal = 17000;
22 | rate = 0.027;
23 | interest = principal * rate; // Compute the interest.
24 |
25 | principal = principal + interest;
26 | // Compute value of investment after one year, with interest.
27 | // (Note: The new value replaces the old value of principal.)
28 |
29 | /* Output the results. */
30 |
31 | System.out.print("The interest earned is $");
32 | System.out.println(interest);
33 | System.out.print("The value of the investment after one year is $");
34 | System.out.println(principal);
35 |
36 | } // end of main()
37 |
38 | } // end of class Interest
39 |
--------------------------------------------------------------------------------
/javanotes9/src-c2/Interest2.java:
--------------------------------------------------------------------------------
1 | import textio.TextIO;
2 |
3 | /**
4 | * This class implements a simple program that will compute
5 | * the amount of interest that is earned on an investment over
6 | * a period of one year. The initial amount of the investment
7 | * and the interest rate are input by the user. The value of
8 | * the investment at the end of the year is output. The
9 | * rate must be input as a decimal, not a percentage (for
10 | * example, 0.05 rather than 5).
11 | *
12 | * This program requires TextIO for input. TextIO is not a
13 | * standard part of Java, so it must be made available when
14 | * the program is compiled or run.
15 | */
16 | public class Interest2 {
17 |
18 | public static void main(String[] args) {
19 |
20 | double principal; // The value of the investment.
21 | double rate; // The annual interest rate.
22 | double interest; // The interest earned during the year.
23 |
24 | System.out.print("Enter the initial investment: ");
25 | principal = TextIO.getlnDouble();
26 |
27 | System.out.print("Enter the annual interest rate (as a decimal): ");
28 | rate = TextIO.getlnDouble();
29 |
30 | interest = principal * rate; // Compute this year's interest.
31 | principal = principal + interest; // Add it to principal.
32 |
33 | System.out.printf("The amount of interest is $%1.2f%n", interest);
34 | System.out.printf("The value after one year is $%1.2f%n", principal);
35 |
36 | } // end of main()
37 |
38 | } // end of class Interest2
39 |
--------------------------------------------------------------------------------
/javanotes9/src-c2/Interest2WithScanner.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner; // Make the Scanner class available.
2 |
3 | /**
4 | * This class implements a simple program that will compute
5 | * the amount of interest that is earned on an investment over
6 | * a period of one year. The initial amount of the investment
7 | * and the interest rate are input by the user. The value of
8 | * the investment at the end of the year is output. The
9 | * rate must be input as a decimal, not a percentage (for
10 | * example, 0.05 rather than 5).
11 | *
12 | * This program uses the standard Scanner class for input.
13 | */
14 | public class Interest2WithScanner {
15 |
16 | public static void main(String[] args) {
17 |
18 | Scanner stdin = new Scanner( System.in ); // Create the Scanner.
19 |
20 | double principal; // The value of the investment.
21 | double rate; // The annual interest rate.
22 | double interest; // The interest earned during the year.
23 |
24 | System.out.print("Enter the initial investment: ");
25 | principal = stdin.nextDouble();
26 |
27 | System.out.print("Enter the annual interest rate (as a decimal): ");
28 | rate = stdin.nextDouble();
29 |
30 | interest = principal * rate; // Compute this year's interest.
31 | principal = principal + interest; // Add it to principal.
32 |
33 | System.out.printf("The amount of interest is $%1.2f%n", interest);
34 | System.out.printf("The value after one year is $%1.2f%n", principal);
35 |
36 | } // end of main()
37 |
38 | } // end of class Interest2WithScanner
--------------------------------------------------------------------------------
/javanotes9/src-c2/Month.java:
--------------------------------------------------------------------------------
1 | /**
2 | * This file defines an enum representing the months of the year.
3 | */
4 | public enum Month {
5 | JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
6 | }
7 |
--------------------------------------------------------------------------------
/javanotes9/src-c2/PrintSquare.java:
--------------------------------------------------------------------------------
1 | import textio.TextIO;
2 |
3 | /**
4 | * A program that reads an integer that is typed in by the
5 | * user and computes and prints the square of that integer.
6 | */
7 | public class PrintSquare {
8 |
9 | public static void main(String[] args) {
10 |
11 | int userInput; // The number input by the user.
12 | int square; // The userInput, multiplied by itself.
13 |
14 | System.out.print("Please type a number: ");
15 | userInput = TextIO.getlnInt();
16 | square = userInput * userInput;
17 |
18 | System.out.println();
19 | System.out.println("The number that you entered was " + userInput);
20 | System.out.println("The square of that number is " + square);
21 | System.out.println();
22 |
23 | } // end of main()
24 |
25 | } //end of class PrintSquare
26 |
--------------------------------------------------------------------------------
/javanotes9/src-c2/SeparateEnumDemo.java:
--------------------------------------------------------------------------------
1 | /**
2 | * This program demonstrates the use of enum types.
3 | *
4 | * For this version of the program, the enum types are defined in
5 | * separate files, Day.java and Month.java. The version named
6 | * EnumDemo.java defines the enums in the same file.
7 | */
8 | public class SeparateEnumDemo {
9 |
10 | public static void main(String[] args) {
11 |
12 | Day tgif; // Declare a variable of type Day.
13 | Month libra; // Declare a variable of type Month.
14 |
15 | tgif = Day.FRIDAY; // Assign a value of type Day to tgif.
16 | libra = Month.OCT; // Assign a value of type Month to libra.
17 |
18 | System.out.print("My sign is libra, since I was born in ");
19 | System.out.println(libra); // Output value will be: OCT
20 | System.out.print("That's the ");
21 | System.out.print( libra.ordinal() );
22 | System.out.println("-th month of the year.");
23 | System.out.println(" (Counting from 0, of course!)");
24 |
25 | System.out.print("Isn't it nice to get to ");
26 | System.out.println(tgif); // Output value will be: FRIDAY
27 |
28 | System.out.println( tgif + " is the " + tgif.ordinal()
29 | + "-th day of the week.");
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/javanotes9/src-c2/TextBlockDemo.java:
--------------------------------------------------------------------------------
1 | /* This program demonstrates text blocks. A text block
2 | * is a string literal that extends over several lines. It begins
3 | * and ends with a triple double-quote ("""). The opening triple
4 | * quote must be followed (except for whitespace) by a newline, which
5 | * is not part of the string represented by the literal. Text blocks
6 | * make it easier to use multiline strings in a Java program.
7 | */
8 |
9 | public class TextBlockDemo {
10 |
11 | public static void main(String[] args) {
12 |
13 | /* Define a multiline string. Note that extra whitespace
14 | * is stripped from the start of each line -- essentially
15 | * enough is stripped to shove the string over to the
16 | * left margin. */
17 |
18 | String poem = """
19 | As I was walking down the stair,
20 | I met a man who wasn't there.
21 | He wasn't there again today.
22 | I wish, I wish he'd go away!""";
23 |
24 | System.out.println(poem);
25 | System.out.println();
26 |
27 | /* A text block can include escaped characters such as \t, \n,
28 | * and \\. Characters other than '\' are not special in textblocks.
29 | * For example, something that looks like a Java comment inside
30 | * a text block is not a comment; it is part of the string.
31 | * Also note that when the closing """ is on a line by itself,
32 | * then the newline that precedes the """ is part of the string. */
33 |
34 | String program = """
35 | /**
36 | * The standard HelloWorld program.
37 | */
38 | public class HelloWorld {\n
39 | public static void main(String[] args) {
40 | System.out.println("Hello World"); // greet the world!!
41 | }\n
42 | }
43 | """;
44 |
45 | System.out.println(program);
46 |
47 | /* A text block can be used anywhere a string literal could be used,
48 | * such as in a formatted print statement (See Section 2.4.1). */
49 |
50 | int miles = 17;
51 | System.out.printf("""
52 | The equivalent of %d miles is:
53 | %,d yards
54 | %,d feet
55 | %,d inches
56 | """, miles, 1760*miles, 5280*miles, 12*5280*miles);
57 |
58 | }
59 |
60 | } // end TextBlockDemo
61 |
62 |
--------------------------------------------------------------------------------
/javanotes9/src-c2/TimedComputation.java:
--------------------------------------------------------------------------------
1 | /**
2 | * This program performs some mathematical computations and displays the
3 | * results. It also displays the value of the constant Math.PI. It then
4 | * reports the number of seconds that the computer spent on this task.
5 | */
6 | public class TimedComputation {
7 |
8 | public static void main(String[] args) {
9 |
10 | long startTime; // Starting time of program, in nanoseconds.
11 | long endTime; // Time when computations are done, in nanoseconds.
12 | long compTime; // Run time in nanoseconds.
13 | double seconds; // Time difference, in seconds.
14 |
15 | startTime = System.nanoTime();
16 |
17 | double width, height, hypotenuse; // sides of a triangle
18 | width = 42.0;
19 | height = 17.0;
20 | hypotenuse = Math.sqrt( width*width + height*height );
21 | System.out.print("A triangle with sides 42 and 17 has hypotenuse ");
22 | System.out.println(hypotenuse);
23 |
24 | System.out.println("\nMathematically, sin(x)*sin(x) + "
25 | + "cos(x)*cos(x) - 1 should be 0.");
26 | System.out.println("Let's check this for x = 100:");
27 | System.out.print(" sin(100)*sin(100) + cos(100)*cos(100) - 1 is: ");
28 | System.out.println( Math.sin(100)*Math.sin(100)
29 | + Math.cos(100)*Math.cos(100) - 1 );
30 | System.out.println("(There can be round-off errors when"
31 | + " computing with real numbers!)");
32 |
33 | System.out.print("\nHere is a random number: ");
34 | System.out.println( Math.random() );
35 |
36 | System.out.print("\nThe value of Math.PI is ");
37 | System.out.println( Math.PI );
38 |
39 | endTime = System.nanoTime();
40 | compTime = endTime - startTime;
41 | seconds = compTime / 1000000000.0;
42 |
43 | System.out.print("\nRun time in nanoseconds was: ");
44 | System.out.println(compTime);
45 | System.out.println("(This is probably not perfectly accurate!");
46 | System.out.print("\nRun time in seconds was: ");
47 | System.out.println(seconds);
48 |
49 | } // end main()
50 |
51 | } // end class TimedComputation
52 |
53 |
--------------------------------------------------------------------------------
/javanotes9/src-c3/BirthdayProblem.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Simulate choosing people at random and checking the day of the year they
3 | * were born on. If the birthday is the same as one that was seen previously,
4 | * stop, and output the number of people who were checked.
5 | */
6 | public class BirthdayProblem {
7 |
8 | public static void main(String[] args) {
9 |
10 | boolean[] used; // For recording the possible birthdays
11 | // that have been seen so far. A value
12 | // of true in used[i] means that a person
13 | // whose birthday is the i-th day of the
14 | // year has been found.
15 |
16 | int count; // The number of people who have been checked.
17 |
18 | used = new boolean[365]; // Initially, all entries are false.
19 |
20 | count = 0;
21 |
22 | while (true) {
23 | // Select a birthday at random, from 0 to 364.
24 | // If the birthday has already been used, quit.
25 | // Otherwise, record the birthday as used.
26 |
27 | int birthday; // The selected birthday.
28 | birthday = (int)(Math.random()*365);
29 | count++;
30 |
31 | System.out.printf("Person %d has birthday number %d%n", count, birthday);
32 |
33 | if ( used[birthday] ) {
34 | // This day was found before; It's a duplicate. We are done.
35 | break;
36 | }
37 |
38 | used[birthday] = true;
39 |
40 | } // end while
41 |
42 | System.out.println();
43 | System.out.println("A duplicate birthday was found after "
44 | + count + " tries.");
45 | }
46 |
47 | } // end class BirthdayProblem
--------------------------------------------------------------------------------
/javanotes9/src-c3/ComputeAverage.java:
--------------------------------------------------------------------------------
1 | import textio.TextIO;
2 |
3 | /**
4 | * This program reads a sequence of positive integers input
5 | * by the user, and it will print out the average of those
6 | * integers. The user is prompted to enter one integer at a
7 | * time. The user must enter a 0 to mark the end of the
8 | * data. (The zero is not counted as part of the data to
9 | * be averaged.) The program does not check whether the
10 | * user's input is positive, so it will actually add up
11 | * both positive and negative input values.
12 | */
13 |
14 | public class ComputeAverage {
15 |
16 | public static void main(String[] args) {
17 |
18 | int inputNumber; // One of the integers input by the user.
19 | int sum; // The sum of the positive integers.
20 | int count; // The number of positive integers.
21 | double average; // The average of the positive integers.
22 |
23 | /* Initialize the summation and counting variables. */
24 |
25 | sum = 0;
26 | count = 0;
27 |
28 | /* Read and process the user's input. */
29 |
30 | System.out.print("Enter your first positive integer: ");
31 | inputNumber = TextIO.getlnInt();
32 |
33 | while (inputNumber != 0) {
34 | sum += inputNumber; // Add inputNumber to running sum.
35 | count++; // Count the input by adding 1 to count.
36 | System.out.print("Enter your next positive integer, or 0 to end: ");
37 | inputNumber = TextIO.getlnInt();
38 | }
39 |
40 | /* Display the result. */
41 |
42 | if (count == 0) {
43 | System.out.println("You didn't enter any data!");
44 | }
45 | else {
46 | average = ((double)sum) / count;
47 | System.out.println();
48 | System.out.println("You entered " + count + " positive integers.");
49 | System.out.printf("Their average is %1.3f.\n", average);
50 | }
51 |
52 | } // end main()
53 |
54 | } // end class ComputeAverage
--------------------------------------------------------------------------------
/javanotes9/src-c3/ComputeAverage2.java:
--------------------------------------------------------------------------------
1 | import textio.TextIO;
2 |
3 | /**
4 | * Computes the average of a sequence of real numbers entered by the
5 | * user. The numbers must be entered one per line. A blank input
6 | * line marks the end of the input.
7 | */
8 | public class ComputeAverage2 {
9 |
10 | public static void main(String[] args) {
11 | String str; // The user's input.
12 | double number; // The input converted into a number.
13 | double total; // The total of all numbers entered.
14 | double avg; // The average of the numbers.
15 | int count; // The number of numbers entered.
16 | total = 0;
17 | count = 0;
18 | System.out.println("Enter your numbers, press return to end.");
19 | while (true) {
20 | System.out.print("? ");
21 | str = TextIO.getln();
22 | if (str.equals("")) {
23 | break; // Exit the loop, since the input line was blank.
24 | }
25 | try {
26 | number = Double.parseDouble(str);
27 | // If an error occurs, the next 2 lines are skipped!
28 | total = total + number;
29 | count = count + 1;
30 | }
31 | catch (NumberFormatException e) {
32 | System.out.println("Not a legal number! Try again.");
33 | }
34 | }
35 | avg = total/count;
36 | System.out.printf("The average of %d numbers is %1.6g%n", count, avg);
37 | }
38 |
39 | }
--------------------------------------------------------------------------------
/javanotes9/src-c3/Interest3.java:
--------------------------------------------------------------------------------
1 | import textio.TextIO;
2 |
3 | /**
4 | * This class implements a simple program that will compute the amount of
5 | * interest that is earned on an investment over a period of 5 years. The
6 | * initial amount of the investment and the interest rate are input by the
7 | * user. The value of the investment at the end of each year is output.
8 | */
9 |
10 | public class Interest3 {
11 |
12 |
13 | public static void main(String[] args) {
14 |
15 | double principal; // The value of the investment.
16 | double rate; // The annual interest rate.
17 |
18 | /* Get the initial investment and interest rate from the user. */
19 |
20 | System.out.print("Enter the initial investment: ");
21 | principal = TextIO.getlnDouble();
22 |
23 | System.out.println();
24 | System.out.println("Enter the annual interest rate.");
25 | System.out.print("Enter a decimal, not a percentage: ");
26 | rate = TextIO.getlnDouble();
27 | System.out.println();
28 |
29 | /* Simulate the investment for 5 years. */
30 |
31 | int years; // Counts the number of years that have passed.
32 |
33 | years = 0;
34 | while (years < 5) {
35 | double interest; // Interest for this year.
36 | interest = principal * rate;
37 | principal = principal + interest; // Add it to principal.
38 | years = years + 1; // Count the current year.
39 | System.out.print("The value of the investment after ");
40 | System.out.print(years);
41 | System.out.print(" years is $");
42 | System.out.printf("%1.2f", principal);
43 | System.out.println();
44 | } // end of while loop
45 |
46 | } // end of main()
47 |
48 | } // end of class Interest3
49 |
--------------------------------------------------------------------------------
/javanotes9/src-c3/ListLetters.java:
--------------------------------------------------------------------------------
1 | import textio.TextIO;
2 |
3 | /**
4 | * This program reads a line of text entered by the user.
5 | * It prints a list of the letters that occur in the text,
6 | * and it reports how many different letters were found.
7 | */
8 |
9 | public class ListLetters {
10 |
11 | public static void main(String[] args) {
12 |
13 | String str; // Line of text entered by the user.
14 | int count; // Number of different letters found in str.
15 | char letter; // A letter of the alphabet.
16 |
17 | System.out.println("Please type in a line of text.");
18 | str = TextIO.getln();
19 |
20 | str = str.toUpperCase();
21 |
22 | count = 0;
23 | System.out.println("Your input contains the following letters:");
24 | System.out.println();
25 | System.out.print(" ");
26 | for ( letter = 'A'; letter <= 'Z'; letter++ ) {
27 | int i; // Position of a character in str.
28 | for ( i = 0; i < str.length(); i++ ) {
29 | if ( letter == str.charAt(i) ) {
30 | System.out.print(letter);
31 | System.out.print(' ');
32 | count++;
33 | break;
34 | }
35 | }
36 | }
37 |
38 | System.out.println();
39 | System.out.println();
40 | System.out.println("There were " + count + " different letters.");
41 |
42 | } // end main()
43 |
44 | } // end class ListLetters
45 |
--------------------------------------------------------------------------------
/javanotes9/src-c3/ReverseInputNumbers.java:
--------------------------------------------------------------------------------
1 | import textio.TextIO;
2 |
3 | /**
4 | * Reads up to 100 integers from the user, then prints them
5 | * in reverse order. An input of zero marks the end of input.
6 | */
7 | public class ReverseInputNumbers {
8 |
9 | public static void main(String[] args) {
10 |
11 | int[] numbers; // An array for storing the input values.
12 | int count; // The number of numbers saved in the array.
13 | int num; // One of the numbers input by the user.
14 | int i; // for-loop variable.
15 |
16 | numbers = new int[100]; // Space for 100 ints.
17 | count = 0; // No numbers have been saved yet.
18 |
19 | System.out.println("Enter up to 100 positive integers; enter 0 to end.");
20 |
21 | while (true) { // Get the numbers and put them in the array.
22 | System.out.print("? ");
23 | num = TextIO.getlnInt();
24 | if (num <= 0) {
25 | // Zero marks the end of input; we have all the numbers.
26 | break;
27 | }
28 | numbers[count] = num; // Put num in position count.
29 | count++; // Count the number
30 | }
31 |
32 | System.out.println("\nYour numbers in reverse order are:\n");
33 |
34 | for ( i = count - 1; i >= 0; i-- ) {
35 | System.out.println( numbers[i] );
36 | }
37 |
38 | } // end main();
39 |
40 | } // end class ReverseInputNumbers
41 |
--------------------------------------------------------------------------------
/javanotes9/src-c3/ThreeN1.java:
--------------------------------------------------------------------------------
1 | import textio.TextIO;
2 |
3 | /**
4 | * This program prints out a 3N+1 sequence starting from a positive
5 | * integer specified by the user. It also counts the number of
6 | * terms in the sequence, and prints out that number.
7 | */
8 | public class ThreeN1 {
9 |
10 | public static void main(String[] args) {
11 |
12 | int N; // for computing terms in the sequence
13 | int counter; // for counting the terms
14 |
15 | System.out.print("Starting point for sequence: ");
16 | N = TextIO.getlnInt();
17 | while (N <= 0) {
18 | System.out.print("The starting point must be positive. Please try again: ");
19 | N = TextIO.getlnInt();
20 | }
21 | // At this point, we know that N > 0
22 |
23 | counter = 0;
24 | while (N != 1) {
25 | if (N % 2 == 0)
26 | N = N / 2;
27 | else
28 | N = 3 * N + 1;
29 | System.out.println(N);
30 | counter = counter + 1;
31 | }
32 |
33 | System.out.println();
34 | System.out.print("There were ");
35 | System.out.print(counter);
36 | System.out.println(" terms in the sequence.");
37 |
38 | } // end of main()
39 |
40 | } // end of class ThreeN1
41 |
--------------------------------------------------------------------------------
/javanotes9/src-c4/ArrayProcessor.java:
--------------------------------------------------------------------------------
1 |
2 | /**
3 | * A functional interface that defines a function
4 | * that has one parameter of type double[] and that
5 | * returns a value of type double.
6 | */
7 | public interface ArrayProcessor {
8 |
9 | double apply( double[] array );
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/javanotes9/src-c4/CopyTextFile.java:
--------------------------------------------------------------------------------
1 | import textio.TextIO;
2 |
3 | /**
4 | * Requires two command line arguments, which must be file names. The
5 | * the first must be the name of an existing file. The second is the name
6 | * of a file to be created by the program. The contents of the first file
7 | * are copied into the second. WARNING: If the second file already
8 | * exists when the program is run, its previous contents will be lost!
9 | * This program only works for plain text files.
10 | */
11 | public class CopyTextFile {
12 |
13 | public static void main( String[] args ) {
14 | if (args.length < 2 ) {
15 | System.out.println("Two command-line arguments are required!");
16 | System.exit(1);
17 | }
18 | TextIO.readFile( args[0] ); // Open the original file for reading.
19 | TextIO.writeFile( args[1] ); // Open the copy file for writing.
20 | int lineCount; // Number of lines copied
21 | lineCount = 0;
22 | while ( TextIO.eof() == false ) {
23 | // Read one line from the original file and write it to the copy.
24 | String line;
25 | line = TextIO.getln();
26 | TextIO.putln(line);
27 | lineCount++;
28 | }
29 | System.out.printf( "%d lines copied from %s to %s%n",
30 | lineCount, args[0], args[1] );
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/javanotes9/src-c4/RowsOfChars.java:
--------------------------------------------------------------------------------
1 | import textio.TextIO;
2 |
3 | /**
4 | * This program will get a line of input from the user. It will
5 | * then output one line for each character in the user's input. That
6 | * line will contain 25 copies of the character.
7 | *
8 | * This simple program is meant to demonstrate the use of subroutines,
9 | * and especially the case where one routine calls a subroutine
10 | * which then calls another subroutine. It is not a useful program.
11 | *
12 | * (Note: It doesn't matter in what order the subroutines are
13 | * listed in the class. A subroutine can always be used anywhere
14 | * in the class that defines it, even if the definition occurs
15 | * physically after the point where it is called.)
16 | */
17 | public class RowsOfChars {
18 |
19 | public static void main(String[] args) {
20 | String inputLine; // Line of text input by user.
21 | TextIO.put("Enter a line of text: ");
22 | inputLine = TextIO.getln();
23 | TextIO.putln();
24 | printRowsFromString( inputLine );
25 | }
26 |
27 |
28 | /**
29 | * For each character in str, write a line of output
30 | * containing 25 copies of that character.
31 | */
32 | private static void printRowsFromString( String str ) {
33 | int i; // Loop-control variable for counting off the chars.
34 | for ( i = 0; i < str.length(); i++ ) {
35 | printRow( str.charAt(i), 25 );
36 | }
37 | }
38 |
39 |
40 | /**
41 | * Write one line of output containing N copies of the
42 | * character ch. If N is less than or equal to 0, an empty line is output.
43 | */
44 | private static void printRow( char ch, int N ) {
45 | int i; // Loop-control variable for counting off the copies.
46 | for ( i = 1; i <= N; i++ ) {
47 | System.out.print( ch );
48 | }
49 | System.out.println();
50 | }
51 |
52 |
53 | } //end of class RowsOfChars
54 |
--------------------------------------------------------------------------------
/javanotes9/src-c5/BlackjackHand.java:
--------------------------------------------------------------------------------
1 | public class BlackjackHand extends Hand {
2 |
3 | /**
4 | * Computes and returns the value of this hand in the game
5 | * of Blackjack.
6 | */
7 | public int getBlackjackValue() {
8 |
9 | int val; // The value computed for the hand.
10 | boolean ace; // This will be set to true if the
11 | // hand contains an ace.
12 | int cards; // Number of cards in the hand.
13 |
14 | val = 0;
15 | ace = false;
16 | cards = getCardCount(); // (method defined in class Hand.)
17 |
18 | for ( int i = 0; i < cards; i++ ) {
19 | // Add the value of the i-th card in the hand.
20 | Card card; // The i-th card;
21 | int cardVal; // The blackjack value of the i-th card.
22 | card = getCard(i);
23 | cardVal = card.getValue(); // The normal value, 1 to 13.
24 | if (cardVal > 10) {
25 | cardVal = 10; // For a Jack, Queen, or King.
26 | }
27 | if (cardVal == 1) {
28 | ace = true; // There is at least one ace.
29 | }
30 | val = val + cardVal;
31 | }
32 |
33 | // Now, val is the value of the hand, counting any ace as 1.
34 | // If there is an ace, and if changing its value from 1 to
35 | // 11 would leave the score less than or equal to 21,
36 | // then do so by adding the extra 10 points to val.
37 |
38 | if ( ace == true && val + 10 <= 21 )
39 | val = val + 10;
40 |
41 | return val;
42 |
43 | } // end getBlackjackValue()
44 |
45 | } // end class BlackjackHand
46 |
--------------------------------------------------------------------------------
/javanotes9/src-c5/CircleInfo.java:
--------------------------------------------------------------------------------
1 | import javafx.scene.paint.Color;
2 | import javafx.scene.canvas.GraphicsContext;
3 |
4 | /**
5 | * A simple class that holds the size, color, and location of a colored disk,
6 | * with a method for drawing the circle in a graphics context. The circle
7 | * is drawn as a filled oval, with a black outline.
8 | */
9 | public class CircleInfo {
10 |
11 | public int radius; // The radius of the circle.
12 | public int x,y; // The location of the center of the circle.
13 | public Color color; // The color of the circle.
14 |
15 | /**
16 | * Create a CircleInfo with a given location and radius and with a
17 | * randomly selected, semi-transparent color.
18 | * @param centerX The x coordinate of the center.
19 | * @param centerY The y coordinate of the center.
20 | * @param rad The radius of the circle.
21 | */
22 | public CircleInfo( int centerX, int centerY, int rad ) {
23 | x = centerX;
24 | y = centerY;
25 | radius = rad;
26 | double red = Math.random();
27 | double green = Math.random();
28 | double blue = Math.random();
29 | color = new Color(red,green,blue, 0.4);
30 | }
31 |
32 | /**
33 | * Draw the disk in graphics context g, with a black outline.
34 | */
35 | public void draw( GraphicsContext g ) {
36 | g.setFill( color );
37 | g.fillOval( x - radius, y - radius, 2*radius, 2*radius );
38 | g.setStroke( Color.BLACK );
39 | g.strokeOval( x - radius, y - radius, 2*radius, 2*radius );
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/javanotes9/src-c5/PairOfDice.java:
--------------------------------------------------------------------------------
1 | /**
2 | * A PairOfDice object represents an ordinary pair of six-sided dice.
3 | */
4 | public class PairOfDice {
5 |
6 | public int die1; // Number showing on the first die.
7 | public int die2; // Number showing on the second die.
8 |
9 | public PairOfDice() {
10 | // Constructor. Rolls the dice, so that they initially
11 | // show some random values.
12 | roll(); // Call the roll() method to roll the dice.
13 | }
14 |
15 | public PairOfDice(int val1, int val2) {
16 | // Constructor. Creates a pair of dice that
17 | // are initially showing the values val1 and val2.
18 | die1 = val1; // Assign specified values
19 | die2 = val2; // to the instance variables.
20 | }
21 |
22 | public void roll() {
23 | // Roll the dice by setting each of the dice to be
24 | // a random number between 1 and 6.
25 | die1 = (int)(Math.random()*6) + 1;
26 | die2 = (int)(Math.random()*6) + 1;
27 | }
28 |
29 | } // end class PairOfDice
30 |
--------------------------------------------------------------------------------
/javanotes9/src-c5/RollTwoPairs.java:
--------------------------------------------------------------------------------
1 |
2 | /**
3 | * This program creates two PairOfDice objects and rolls them over and over
4 | * until the totals on the two pairs are the same. It reports how many
5 | * times the dice were rolled.
6 | */
7 | public class RollTwoPairs {
8 |
9 | public static void main(String[] args) {
10 |
11 | PairOfDice firstDice; // Refers to the first pair of dice.
12 | firstDice = new PairOfDice();
13 |
14 | PairOfDice secondDice; // Refers to the second pair of dice.
15 | secondDice = new PairOfDice();
16 |
17 | int countRolls; // Counts how many times the two pairs of
18 | // dice have been rolled.
19 |
20 | int total1; // Total showing on first pair of dice.
21 | int total2; // Total showing on second pair of dice.
22 |
23 | countRolls = 0;
24 |
25 | do { // Roll the two pairs of dice until totals are the same.
26 |
27 | firstDice.roll(); // Roll the first pair of dice.
28 | total1 = firstDice.die1 + firstDice.die2; // Get total.
29 | System.out.println("First pair comes up " + total1);
30 |
31 | secondDice.roll(); // Roll the second pair of dice.
32 | total2 = secondDice.die1 + secondDice.die2; // Get total.
33 | System.out.println("Second pair comes up " + total2);
34 |
35 | countRolls++; // Count this roll.
36 |
37 | System.out.println(); // Blank line.
38 |
39 | } while (total1 != total2);
40 |
41 | System.out.println("It took " + countRolls
42 | + " rolls until the totals were the same.");
43 |
44 | } // end main()
45 |
46 | } // end class RollTwoPairs
47 |
--------------------------------------------------------------------------------
/javanotes9/src-c5/StatCalc.java:
--------------------------------------------------------------------------------
1 | /**
2 | * An object of class StatCalc can be used to compute several simple statistics
3 | * for a set of numbers. Numbers are entered into the dataset using
4 | * the enter(double) method. Methods are provided to return the following
5 | * statistics for the set of numbers that have been entered: The number
6 | * of items, the sum of the items, the average, and the standard deviation
7 | */
8 |
9 | public class StatCalc {
10 |
11 | private int count; // Number of numbers that have been entered.
12 | private double sum; // The sum of all the items that have been entered.
13 | private double squareSum; // The sum of the squares of all the items.
14 |
15 | /**
16 | * Add a number to the dataset. The statistics will be computed for all
17 | * the numbers that have been added to the dataset using this method.
18 | */
19 | public void enter(double num) {
20 | count++;
21 | sum += num;
22 | squareSum += num*num;
23 | }
24 |
25 | /**
26 | * Return the number of items that have been entered into the dataset.
27 | */
28 | public int getCount() {
29 | return count;
30 | }
31 |
32 | /**
33 | * Return the sum of all the numbers that have been entered.
34 | */
35 | public double getSum() {
36 | return sum;
37 | }
38 |
39 | /**
40 | * Return the average of all the items that have been entered.
41 | * The return value is Double.NaN if no numbers have been entered.
42 | */
43 | public double getMean() {
44 | return sum / count;
45 | }
46 |
47 | /**
48 | * Return the standard deviation of all the items that have been entered.
49 | * The return value is Double.NaN if no numbers have been entered.
50 | */
51 | public double getStandardDeviation() {
52 | double mean = getMean();
53 | return Math.sqrt( squareSum/count - mean*mean );
54 | }
55 |
56 | } // end class StatCalc
57 |
--------------------------------------------------------------------------------
/javanotes9/src-c6/HelloWorldFX.java:
--------------------------------------------------------------------------------
1 | import javafx.application.Application;
2 | import javafx.scene.Scene;
3 | import javafx.stage.Stage;
4 | import javafx.application.Platform;
5 | import javafx.scene.layout.BorderPane;
6 | import javafx.scene.layout.HBox;
7 | import javafx.geometry.Pos;
8 | import javafx.scene.control.Label;
9 | import javafx.scene.control.Button;
10 | import javafx.scene.text.Font;
11 |
12 | public class HelloWorldFX extends Application {
13 |
14 | public void start(Stage stage) {
15 |
16 | Label message = new Label("First FX Application!");
17 | message.setFont( new Font(40) );
18 |
19 | Button helloButton = new Button("Say Hello");
20 | helloButton.setOnAction( evt -> message.setText("Hello World!") );
21 | Button goodbyeButton = new Button("Say Goodbye");
22 | goodbyeButton.setOnAction( evt -> message.setText("Goodbye!!") );
23 | Button quitButton = new Button("Quit");
24 | quitButton.setOnAction( evt -> Platform.exit() );
25 |
26 | HBox buttonBar = new HBox( 20, helloButton, goodbyeButton, quitButton );
27 | buttonBar.setAlignment(Pos.CENTER);
28 | BorderPane root = new BorderPane();
29 | root.setCenter(message);
30 | root.setBottom(buttonBar);
31 |
32 | Scene scene = new Scene(root, 450, 200);
33 | stage.setScene(scene);
34 | stage.setTitle("JavaFX Test");
35 | stage.show();
36 |
37 | } // end start();
38 |
39 | public static void main(String[] args) {
40 | launch(); // Run this Application.
41 | }
42 |
43 | } // end class HelloWorldFX
--------------------------------------------------------------------------------
/javanotes9/src-c6/cards.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidjeck/javanotes9/6a36faf886c5ffa32a06fb0d416946801ac9b225/javanotes9/src-c6/cards.png
--------------------------------------------------------------------------------
/javanotes9/src-c7/Complex.java:
--------------------------------------------------------------------------------
1 | /**
2 | * A record type for representing complex numbers, where
3 | * a complex number consists of two real numbers called its
4 | * real and imaginary parts. The class includes methods for
5 | * doing arithmetic with complex numbers.
6 | */
7 | public record Complex(double re, double im) {
8 |
9 | // Some named constants for common complex numbers.
10 |
11 | public final static Complex ONE = new Complex(1,0);
12 | public final static Complex ZERO = new Complex(0,0);
13 | public final static Complex I = new Complex(0,1);
14 |
15 | /**
16 | * This constructor creates a complex number with a given
17 | * real part and with imaginary part zero.
18 | */
19 | public Complex(double re) {
20 | this(re,0);
21 | }
22 |
23 | /**
24 | * Creates string representations of complex number such
25 | * as: 3.0 + I*5.0, -I*3.14, 2.7 - I*8.6, 3.14
26 | */
27 | public String toString() {
28 | if (im == 0)
29 | return String.valueOf(re);
30 | else if (re == 0) {
31 | if (im < 0)
32 | return "-I*" + (-im);
33 | else
34 | return "I*" + im;
35 | }
36 | else if (im < 0)
37 | return re + " - " + "I*" + (-im);
38 | else
39 | return re + " + " + "I*" + im;
40 | }
41 |
42 | // Some methods for doing arithmetic on two complex numbers
43 |
44 | public Complex plus(Complex c) {
45 | return new Complex(re + c.re, im + c.im);
46 | }
47 | public Complex minus(Complex c) {
48 | return new Complex(re - c.re, im - c.im);
49 | }
50 | public Complex times(Complex c) {
51 | return new Complex(re*c.re - im*c.im,
52 | re*c.im + im*c.re);
53 | }
54 | public Complex dividedBy(Complex c) {
55 | double denom = c.re*c.re + c.im*c.im;
56 | double real = (re*c.re + im*c.im)/denom;
57 | double imaginary = (im*c.re - re*c.im)/denom;
58 | return new Complex(real,imaginary);
59 | }
60 |
61 | } // end record Complex
62 |
63 |
--------------------------------------------------------------------------------
/javanotes9/src-c7/DynamicArrayOfInt.java:
--------------------------------------------------------------------------------
1 | import java.util.Arrays;
2 |
3 | /**
4 | * Represents a list of int values that can grow and shrink.
5 | */
6 | public class DynamicArrayOfInt {
7 |
8 | private int[] items = new int[8]; // partially full array holding the ints
9 | private int itemCt;
10 |
11 | /**
12 | * Return the item at a given index in the array.
13 | * Throws ArrayIndexOutOfBoundsException if the index is not valid.
14 | */
15 | public int get( int index ) {
16 | if ( index < 0 || index >= itemCt )
17 | throw new ArrayIndexOutOfBoundsException("Illegal index, " + index);
18 | return items[index];
19 | }
20 |
21 | /**
22 | * Set the value of the array element at a given index.
23 | * Throws ArrayIndexOutOfBoundsException if the index is not valid.
24 | */
25 | public void set( int index, int item ) {
26 | if ( index < 0 || index >= itemCt )
27 | throw new ArrayIndexOutOfBoundsException("Illegal index, " + index);
28 | items[index] = item;
29 | }
30 |
31 | /**
32 | * Returns the number of items currently in the array.
33 | */
34 | public int size() {
35 | return itemCt;
36 | }
37 |
38 | /**
39 | * Adds a new item to the end of the array. The size increases by one.
40 | */
41 | public void add(int item) {
42 | if (itemCt == items.length)
43 | items = Arrays.copyOf( items, 2*items.length );
44 | items[itemCt] = item;
45 | itemCt++;
46 | }
47 |
48 | /**
49 | * Removes the item at a given index in the array. The size of the array
50 | * decreases by one. Items following the removed item are moved down
51 | * one space in the array.
52 | * Throws ArrayIndexOutOfBoundsException if the index is not valid.
53 | */
54 | public void remove(int index) {
55 | if ( index < 0 || index >= itemCt )
56 | throw new ArrayIndexOutOfBoundsException("Illegal index, " + index);
57 | for (int j = index+1; j < itemCt; j++)
58 | items[j-1] = items[j];
59 | itemCt--;
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/javanotes9/src-c7/FullName.java:
--------------------------------------------------------------------------------
1 |
2 | /**
3 | * A record class for representing names. A name consists of a
4 | * first name and a last name. However, to accommodate people
5 | * who use only one name, the last name can be null.
6 | */
7 | public record FullName(String firstName, String lastName) {
8 |
9 | /**
10 | * Canonical constructor takes two parameters representing
11 | * the first name and the last name. The last name can be
12 | * null, but if the first name is null an IllegalArgumentException
13 | * will be thrown.
14 | */
15 | public FullName {
16 | if (firstName == null) {
17 | throw new IllegalArgumentException("First name can't be null.");
18 | }
19 | }
20 |
21 | /**
22 | * Constructor for creating a FullName for a person who uses
23 | * only one name. The parameter represents that name, which
24 | * becomes the firstName field of the FullName. The lastName
25 | * field is null.
26 | */
27 | public FullName(String name) {
28 | this(name,null);
29 | }
30 |
31 | /**
32 | * For a person who uses only one name, returns that name.
33 | * Otherwise, returns a string containing the first name
34 | * and the last name, separated by a space.
35 | */
36 | public String toString() {
37 | if (lastName == null)
38 | return firstName;
39 | else
40 | return firstName + " " + lastName;
41 | }
42 |
43 | /**
44 | * Returns true if this FullName is the name of a person
45 | * who uses only one name.
46 | */
47 | public boolean oneNameOnly() {
48 | return lastName == null;
49 | }
50 |
51 | } // end record FullName
52 |
53 |
--------------------------------------------------------------------------------
/javanotes9/src-c7/ReverseWithArrayList.java:
--------------------------------------------------------------------------------
1 | import textio.TextIO;
2 | import java.util.ArrayList;
3 |
4 | /**
5 | * Reads a list of non-zero numbers for the user, then prints
6 | * out the input numbers in the reverse of the order in which
7 | * they were entered. there is no limit on the number of inputs.
8 | */
9 | public class ReverseWithArrayList {
10 |
11 | public static void main(String[] args) {
12 | ArrayList list;
13 | list = new ArrayList();
14 | System.out.println("Enter some non-zero integers. Enter 0 to end.");
15 | while (true) {
16 | System.out.print("? ");
17 | int number = TextIO.getlnInt();
18 | if (number == 0)
19 | break;
20 | list.add(number);
21 | }
22 | System.out.println();
23 | System.out.println("Your numbers in reverse are:");
24 | for (int i = list.size() - 1; i >= 0; i--) {
25 | System.out.printf("%10d%n", list.get(i));
26 | }
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/javanotes9/src-c7/ReverseWithDynamicArray.java:
--------------------------------------------------------------------------------
1 | import textio.TextIO;
2 |
3 | /**
4 | * Reads a list of non-zero numbers from the user, then prints
5 | * out the input numbers in the reverse of the order in which
6 | * they were entered. There is no limit on the number of inputs.
7 | */
8 | public class ReverseWithDynamicArray {
9 |
10 | public static void main(String[] args) {
11 | DynamicArrayOfInt list;
12 | list = new DynamicArrayOfInt();
13 | System.out.println("Enter some non-zero integers. Enter 0 to end.");
14 | while (true) {
15 | System.out.print("? ");
16 | int number = TextIO.getlnInt();
17 | if (number == 0)
18 | break;
19 | list.add(number);
20 | }
21 | System.out.println();
22 | System.out.println("Your numbers in reverse are:");
23 | for (int i = list.size() - 1; i >= 0; i--) {
24 | System.out.printf("%10d%n", list.get(i));
25 | }
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/javanotes9/src-c7/SymmetricMatrix.java:
--------------------------------------------------------------------------------
1 |
2 | /**
3 | * Represents symmetric n-by-n matrices of real numbers.
4 | */
5 | public class SymmetricMatrix {
6 |
7 | private double[][] matrix; // A triangular matrix to hold the data.
8 |
9 | /**
10 | * Creates an n-by-n symmetric matrix in which all entries are 0.
11 | */
12 | public SymmetricMatrix(int n) {
13 | matrix = new double[n][];
14 | for (int i = 0; i < n; i++)
15 | matrix[i] = new double[i+1];
16 | }
17 |
18 | /**
19 | * Returns the matrix entry at position (row,col). (If row < col,
20 | * the value is actually stored at position (col,row).)
21 | */
22 | public double get( int row, int col ) {
23 | if (row >= col)
24 | return matrix[row][col];
25 | else
26 | return matrix[col][row];
27 | }
28 |
29 | /**
30 | * Sets the value of the matrix entry at (row,col). (If row < col,
31 | * the value is actually stored at position (col,row).)
32 | */
33 | public void set( int row, int col, double value ) {
34 | if (row >= col)
35 | matrix[row][col] = value;
36 | else
37 | matrix[col][row] = value;
38 | }
39 |
40 | /**
41 | * Returns the number of rows and columns in the matrix.
42 | */
43 | public int size() {
44 | return matrix.length; // The size is the number of rows.
45 | }
46 |
47 | } // end class SymmetricMatrix
48 |
--------------------------------------------------------------------------------
/javanotes9/src-c9/StackOfDouble.java:
--------------------------------------------------------------------------------
1 |
2 | /**
3 | * An object of type StackOfDouble is a stack of real numbers, with the
4 | * standard stack operations push(double N), pop(), and isEmpty().
5 | * Internally, the stack is implemented as a linked list.
6 | */
7 | public class StackOfDouble {
8 |
9 |
10 | /**
11 | * An object of type Node holds one of the items on the stack.
12 | */
13 | private static class Node {
14 | double item; // One of the items in the list
15 | Node next; // Pointer to the node that holds the next item.
16 | }
17 |
18 |
19 | private Node top; // Pointer to the Node that is at the top of the stack.
20 | // If top == null, then the stack is empty.
21 |
22 | /**
23 | * Add N to the top of the stack.
24 | */
25 | public void push( double N ) {
26 | Node newTop = new Node();
27 | newTop.item = N;
28 | newTop.next = top;
29 | top = newTop;
30 | }
31 |
32 | /**
33 | * Remove the top item from the stack, and return it.
34 | * @return the item that was removed from the top of the stack
35 | * @throws IllegalStateException if the stack is empty when method is called.
36 | */
37 | public double pop() {
38 | if ( top == null )
39 | throw new IllegalStateException();
40 | double topItem = top.item;
41 | top = top.next;
42 | return topItem;
43 | }
44 |
45 |
46 | /**
47 | * Returns true if the stack is empty. Returns false
48 | * if there are one or more items on the stack.
49 | */
50 | public boolean isEmpty() {
51 | return top == null;
52 | }
53 |
54 |
55 | } // end class StackOfDouble
56 |
57 |
--------------------------------------------------------------------------------
/javanotes9/src-c9/StackOfInt.java:
--------------------------------------------------------------------------------
1 |
2 | /**
3 | * An object of type StackOfInt is a stack of integerss, with the
4 | * standard stack operations push(int N), pop(), and isEmpty().
5 | * Internally, the stack is implemented as a linked list.
6 | */
7 | public class StackOfInt {
8 |
9 |
10 | /**
11 | * An object of type Node holds one of the items on the stack.
12 | */
13 | private record Node (
14 | int item, // One of the items in the list
15 | Node next // Pointer to the node that holds the next item.
16 | ) { }
17 |
18 |
19 | private Node top; // Pointer to the Node that is at the top of the stack.
20 | // If top == null, then the stack is empty.
21 |
22 | /**
23 | * Add N to the top of the stack.
24 | */
25 | public void push( int N ) {
26 | Node newTop = new Node( N, top );
27 | top = newTop;
28 | }
29 |
30 | /**
31 | * Remove the top item from the stack, and return it.
32 | * @return the item that was removed from the top of the stack
33 | * @throws IllegalStateException if the stack is empty when method is called.
34 | */
35 | public int pop() {
36 | if ( top == null )
37 | throw new IllegalStateException();
38 | int topItem = top.item;
39 | top = top.next;
40 | return topItem;
41 | }
42 |
43 |
44 | /**
45 | * Returns true if the stack is empty. Returns false
46 | * if there are one or more items on the stack.
47 | */
48 | public boolean isEmpty() {
49 | return top == null;
50 | }
51 |
52 |
53 | } // end class StackOfInt
54 |
55 |
--------------------------------------------------------------------------------
/javanotes9/src-c9/TowersOfHanoi.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | /**
4 | * This program lists the steps in the solution of the TowersOfHanoi
5 | * problem. The number of disks to be moved is specified by the user.
6 | * Warning: The number of moves grows very quickly with the number of
7 | * disks!
8 | */
9 | public class TowersOfHanoi {
10 |
11 | public static void main(String[] args) {
12 |
13 | Scanner in = new Scanner(System.in);
14 |
15 | int N; // The number of disks in the original stack,
16 | // as specified by the user.
17 |
18 | System.out.println("This program will list the steps in the solution of");
19 | System.out.println("the Towers of Hanoi problem. You can specify the");
20 | System.out.println("number of disks to be moved. Try it for small numbers");
21 | System.out.println("of disks, like 1, 2, 3, and 4.");
22 | System.out.println();
23 | System.out.println("How many disks are to be moved from Stack 0 to Stack 1?");
24 | System.out.println();
25 | System.out.print("? ");
26 |
27 | N = in.nextInt();
28 |
29 | System.out.println();
30 | System.out.println();
31 |
32 | towersOfHanoi(N, 0, 1, 2); // Print the solution.
33 |
34 | }
35 |
36 | /**
37 | * Solve the problem of moving the number of disks specified
38 | * by the first parameter from the stack specified by the
39 | * second parameter to the stack specified by the third
40 | * parameter. The stack specified by the fourth parameter
41 | * is available for use as a spare. Stacks are specified by
42 | * number: 0, 1, or 2.
43 | */
44 | static void towersOfHanoi(int disks, int from, int to, int spare) {
45 | if (disks == 1) {
46 | // There is only one disk to be moved. Just move it.
47 | System.out.printf("Move disk 1 from stack %d to stack %d%n",
48 | from, to);
49 | }
50 | else {
51 | // Move all but one disk to the spare stack, then
52 | // move the bottom disk, then put all the other
53 | // disks on top of it.
54 | towersOfHanoi(disks-1, from, spare, to);
55 | System.out.printf("Move disk %d from stack %d to stack %d%n",
56 | disks, from, to);
57 | towersOfHanoi(disks-1, spare, to, from);
58 | }
59 | }
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/javanotes9/src-textio/textiogui/System.java:
--------------------------------------------------------------------------------
1 | package textiogui;
2 |
3 | import java.io.PrintWriter;
4 | import java.io.BufferedReader;
5 |
6 | /**
7 | * This is a "fake" System class, for use with the GUI version of
8 | * TextIO. It provides only a few of the capabilities of
9 | * java.lang.System. Note that for this class, System.out
10 | * and System.err are PrintWriters, and System.in is a BufferedReader.
11 | * A few subroutines are provided as simple wrappers for the
12 | * real System class.
13 | */
14 | public class System {
15 |
16 | public static PrintWriter err = TextIO.getOut();
17 | public static PrintWriter out = err;
18 | public static BufferedReader in = TextIO.getIn();
19 |
20 | public static long currentTimeMillis() {
21 | return java.lang.System.currentTimeMillis();
22 | }
23 |
24 | public static long nanoTime() {
25 | return java.lang.System.nanoTime();
26 | }
27 |
28 | public static void exit(int code) {
29 | java.lang.System.exit(code);
30 | }
31 |
32 | public static String getProperty(String name) {
33 | return java.lang.System.getProperty(name);
34 | }
35 |
36 | public static String getProperty(String name, String def) {
37 | return java.lang.System.getProperty(name, def);
38 | }
39 |
40 | public static String lineSeparator() {
41 | return java.lang.System.lineSeparator();
42 | }
43 |
44 | // Returns null, which will cause a NullPointerException if
45 | // an attempt is made to use the console. This is actually
46 | // correct behavior since the GUI version of TextIO is not
47 | // a proper console.
48 | public static java.io.Console console() {
49 | return null;
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/javanotes9/textio-for-windows-jar-files/README.txt:
--------------------------------------------------------------------------------
1 | This folder contains the versions of System.java and TextIO.java
2 | that are used in the Windows script make-jar-files.sh for building
3 | jar files for all of the example programs. These are the same
4 | files that are found in textiogui, but modified to be in package
5 | textio instead of in package textiogui. They should not be used
6 | for any purpose other than with make-jar-files.sh on a Windows
7 | platform.
8 |
--------------------------------------------------------------------------------
/javanotes9/textio-for-windows-jar-files/System.java:
--------------------------------------------------------------------------------
1 | package textio;
2 |
3 | import java.io.PrintWriter;
4 | import java.io.BufferedReader;
5 |
6 | /**
7 | * This is a "fake" System class, for use with the GUI version of
8 | * TextIO. It provides only a few of the capabilities of
9 | * java.lang.System. Note that for this class, System.out
10 | * and System.err are PrintWriters, and System.in is a BufferedReader.
11 | * A few subroutines are provided as simple wrappers for the
12 | * real System class.
13 | */
14 | public class System {
15 |
16 | public static PrintWriter err = TextIO.getOut();
17 | public static PrintWriter out = err;
18 | public static BufferedReader in = TextIO.getIn();
19 |
20 | public static long currentTimeMillis() {
21 | return java.lang.System.currentTimeMillis();
22 | }
23 |
24 | public static long nanoTime() {
25 | return java.lang.System.nanoTime();
26 | }
27 |
28 | public static void exit(int code) {
29 | java.lang.System.exit(code);
30 | }
31 |
32 | public static String getProperty(String name) {
33 | return java.lang.System.getProperty(name);
34 | }
35 |
36 | public static String getProperty(String name, String def) {
37 | return java.lang.System.getProperty(name, def);
38 | }
39 |
40 | public static String lineSeparator() {
41 | return java.lang.System.lineSeparator();
42 | }
43 |
44 | // Returns null, which will cause a NullPointerException if
45 | // an attempt is made to use the console. This is actually
46 | // correct behavior since the GUI version of TextIO is not
47 | // a proper console.
48 | public static java.io.Console console() {
49 | return null;
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------