Announcements Archive:


Nov 20: Note #1 — For Wednesday…

 

Make a copy of EmployeeSort3.java and name it EmployeeSort4.java.  Modify the program as follows.  After sorting the employee records by name, perform two searches for employee records, based on name.  For one of the searches, pick an employee name that exists; for the other, pick an employee name that does not exit.  Output the results of the search on the console in both cases.  Hint: Use the binarySearch() method in the Arrays class. 

 

Next your program should sort the employee records by salary.  Include, as well, the necessary code to determine the number of employees with salaries above a certain threshhold.  Output the results on the console.   Use the binarySearch() method to assist (i.e., do not scan all the records and count the number of records with salaries about the threshhold).  Here is a sample run, using the emp.txt file given earlier.

 

PROMPT>java EmployeeSort4 < emp.txt

Employees (original)...

Smith, $25000.0

Jones, $55000.0

Cheese, $75000.0

Applebee, $25000.0

Simpson, $45000.0

Fredricks, $55000.0

MacKenzie, $250000.0

Clinton, $15000.0

Bush, $16000.0

 

Employees (sorted by name)...

Applebee, $25000.0

Bush, $16000.0

Cheese, $75000.0

Clinton, $15000.0

Fredricks, $55000.0

Jones, $55000.0

MacKenzie, $250000.0

Simpson, $45000.0

Smith, $25000.0

 

Searing for 'Smith'...

Found at position 8

 

Searing for 'Johnson'...

Found at position -6

 

Employees (sorted by salary)...

Clinton, $15000.0

Bush, $16000.0

Applebee, $25000.0

Smith, $25000.0

Simpson, $45000.0

Fredricks, $55000.0

Jones, $55000.0

Cheese, $75000.0

MacKenzie, $250000.0

 

Number of high-paided employees (>$50k): 4

 

(Solution: EmployeeSort4.java )

 


Nov 18: Note #1 — Just to clarify some of the discussion from yesterday’s class, re visibility modifiers (also called “access control modifiers”):

 

Private – members declared private are accessible only to the class itself

Package – members declared with no access modifier are accessible in the class itself and are accessible to, and inheritable by, code in the same package

Protected – members declared protected are accessible in the class itself, and are accessible to, and inheritable by, code in the same package and code in subclasses

Public – members declared public are accessible anywhere the class is accessible, and they are inherited by all subclasses


Nov 17: Note #1 — For Monday…

 

Make a copy of the EmployeeSort2.java program and name it EmployeeSort3.java.  Modify the program so that it outputs the employee records three times: once in the orginal order, once sorted by employee name, and once sorted by employee salary.

(Solution: EmployeeSort3.java to be posted Monday)

 


Nov 16: Note #2 — In Chapter 15, you will visit the subject of interfaces, and, in particular, the Java’s Comparable interface (section 15.8, pp. 635-637).  There is an important typo on p. 635. Horstmann shows how to modify the BankAccount class so that it implements the Comparable interface, but he omits the required “implements Comparable” clause.  The line

 

         public class BankAccount

 

in the middle of page 635, should read

 

         public class BankAccount implements Comparable.

 

Although excluded from the readings in the calendar for COSC 1020, you should probably take a few minutes to read Horstmann’s discussion on interfaces in Chapter 9 (section 7, pp. 362-366).


Nov 16: Note #1 — Typo in Horstmann…  On p. 642, third line in third method on the page, v.length() should read v.length.  Thanks to XiaoDong Weng for pointing this out.


Nov 15: Note #1 — For Friday…

 

Make a copy of EmployeeSort.java and name it EmployeeSort2.java.  Add the necessary code to sort the array of employee records by name and print the result on the console.  Note: You must also modify the Employee class to implement the Comparable interface.  See the City.java near the bottom of this web page for an example of a class that implements the Comparable interface.

(Solution: EmployeeSort2.java )

 

Note: For the EmployeeSort2.java program to work you must modify the source code of the Employee class.  The signature must read

 

public class Employee implements Comparable

 

and the class definition must include a compareTo() method conforming to the “contract” of the Comparable interface, namely,

 

public int compareTo(Object o)

{

     return name.compareTo((Employee)o).getName());

}

 


Nov 10: Note #1 — Please read the sections of the text specified in the calendar.  Here’s a programming challenge for Wednesday. We’ll extend this program later in the week to add features relevant to the readings in Chapters 11 and 15.

 

Write a program called EmployeeSort.java.  The program should read a series of employee records from the standard input until eof is detected.  Add the records to a dynamic array — a Vector object — as they are read.  Once input terminates, copy the contents of the dynamic array into a fixed array; then print the contents of the array on the console.  Define and use a static method to print the array.  We’ll work on the sorting aspects of the program later.  For the moment, just get the basic shell up and running.  Here’s a sample run:

 

PROMPT>type emp.txt

Smith 25000

Jones 55000

Cheese 75000

Applebee 25000

Simpson 45000

Fredricks 55000

MacKenzie 250000

Clinton 15000

Bush 16000

PROMPT>java EmployeeSort < emp.txt

Employees (original)...

Smith, $25000.0

Jones, $55000.0

Cheese, $75000.0

Applebee, $25000.0

Simpson, $45000.0

Fredricks, $55000.0

MacKenzie, $250000.0

Clinton, $15000.0

Bush, $16000.0

PROMPT>

 

(Solution: EmployeeSort.java )


Nov 9: Note #1 — Here’s a brief follow-on to some discussion near the end of yesterday’s class.  It pertains to polymorphism.  In the example program, TotalPayroll.java, we retrieved employee records from a dynamic array (a Vector) and printed them.  The records retrieved were objects, either Employee objects or Manager objects.  We retrieved and printed them as follows:

 

Object o = workers.elementAt(i);

System.out.println(o.toString());  // toString() added for clarify

 

Even though o is an Object reference, the toString() method used in the print statement was either the toString() method of the  Employee class, if the object was an Employee object, or the toString() method of the Manager class, if the object was a Manager object.  As Horstmann states, “in Java, method calls are always determined by the type of the actual object, not the type of the object reference” (p. 360).

 

That’s fine, but what if we only want to print the salary of the employees.  The following statement won’t work:

 

System.out.println(o.getSalary());

 

If you think this is a contradiction to Horstmann’s statement, you’re not alone.  Understanding this is very tricky.  I’ll attempt an explanation  here.  The statement above generates a compiler error because there is no getSalary() method in the Object class.  The reason for the compiler error pertains to the distinction between "compile time" (early binding) and "run time" (late binding).  When the statement above is compiled, all the compiler "knows", or "can determine", is that o is an object reference of the Object class and that getSalary() is a method of some other class, but not the Object class.  That clearly is a problem, at least in the eyes of the compiler.  What if the program were to execute and o was assigned a reference to an object of, say, the BankAccount class?  Clearly, the print statement couldn't work because there is no getSalary() method in the BankAccount class.  To guard against this, the compiler flags an error with the above statement.

 

However the statement

 

System.out.println(o.toString()); // toString() added for clarity

 

works because there is a toString() method of the Object class.  No matter what type of object o refers to, this construct makes sense.  At run-time, a choice can be made on which toString() method to call, based on the type object to which o actually refers.

 

If we really wanted to just print the salaries, then we could use the following statements:

 

Employee e = (Employee)workers.elementAt(i);

System.out.println(e.getSalary());

 

There is a shift in responsibility here.  With the statements above, the onus is on us to ensure that workers only holds Employee objects (or Employee subclass objects).  If for some reason, elementAt(i) returns a BankAccount, we’re in trouble.  A run-time error — an exception — will occur and the program will terminate.


Nov 8: Note #1 — Here is the demo program and data file presented in today’s class: TotalPayroll.java | employees.txt.  For Friday…

 

Make a copy of TotalPayroll.java and name is TotayPayroll2.java.  Modify the program so that it produces output showing the total payroll that the company must pay in a year (salaries plus bonuses).  Remember, the data file can have any number of employee records and they can be a mixture of Employee records and Manager records (in any order).  Here is a sample run with the employees.txt sample data file:

 

PROMPT>java TotalPayroll < employees.txt

Total Payroll: $561034.3

 

(Solution: TotalPayroll2.java )


Nov 6: Note #1Click here to see the quiz that was given in Friday’s class.


Oct 30: Note #1 — This week and next we will study inheritance and arrays, two very important and exciting topics in Java. For inheritance, please Chapter 9 in the text, up to an including section 9.5.  For arrays, please read Chapter 11, up to and including section 11.5.  Please do both of these readings asap, as some of our examples for inheritance will use arrays.  There are some notes and example programs provided below that you should also examine. See “Arrays”, “Vectors”, “Key Points – Arrays and Vectors”, “Defining Classes”, and “Extending Classes”.


Oct 27: Note #1 — Here are the last two iterations of the MyDate class: MyDate.bak6 | MyDate.bak7 . The final version, MyDate.bak7, is a complete implementation of the MyDate class.  Plus, it includes a self-test main() method.  You may want to download MyDate.bak7, change the name to MyDate.java, then compile and execute it.  The solution posted in the course’s main web site is also available here: MyDate.java.  There are a number of differences between the solution we developed and that posted on the course’s main web site.  We’ll discuss these in class.


Oct 26: Note #1 — Here’s quick suggestion for you, if you are having problems getting eCheck to work with Lab #6.  Do not use Math.round() anywhere in your solution!  Math.round() rounds slightly differently from York.format() and Math.rint().  When the double argument is exactly half way between two integers, Math.round() will always round up, whereas York.format() and Math.rint() round to the closest even number.  This is enough of a difference to cause a 1-cent error for some of the test conditions eCheck uses on your program.  And that’s enough to prevent eCheck from giving your program a clean bill of health.  Here’s a program to demonstrate the behaviour just described: DemoRounding.java.


Oct 25: Note #2 — Also for Friday… Finish your implementation of MyDate.java. Here are the versions we developed in class today: MyDate.bak4 | MyDate.bak5


Oct 25: Note #1 — For Friday… work on the Intname2 program.  See Oct 23: Note #1 for details.


Oct 24: Note #1 — Please make sure you read Chapter 7 this week.  I’d like to draw your attention to an important topic that surfaces in this chapter: parameter passing.  The topic has to do with how primitive data types and objects are passed to methods and what you can and cannot do to the original values from within the method.  There are some notes posted in this web site on this topic.  See “Pass by Reference vs. Pass by Value” below.  Spend a few minutes to read this. We’ll talk about this in class on Wednesday (time permitting) and look at the demo program, DemoPassByReference (see below).  You might want to also read the two-page note called “StringBuffer Class” (see below), since a StringBuffer object is used in the demo program.  Horstmann’s take on this is found in the sidebar “Common Error 7.2” on pp. 277-278.  Please read this as well.

 

In Horstmann’s “Advanced Topic 7.1” (pp. 279-280), he twists the terminology a bit, and you might it confusing.  He states on p. 279 that it is “technically not quite correct’ to say that in Java “objects are passed by reference”.  As always, the terminology is a bit tricky.  Horstmann would like us also speak as follows: “objects references are passed by value” (p. 280).  Indeed, this is correct, because it is the value of the reference that is passed, not the object itself.  But, this is really the same as saying, “objects are passed by reference”.  In other words, when you pass an object to a method, it’s the reference (or the “value of the reference”, if you prefer) that you are passing, not the object itself.  Got it?


Oct 23: Note #2 — Also for Friday…  Implement the “get” (accessor) and “set” (mutator) methods in the MyDate class.  Add the appropriate code to the self-test main() method.  Here are partial listings (bugs and all) of the MyDate class, as developed in stages in today’s class: (  MyDate.bak1 | MyDate.bak2 | MyDate.bak3 ). 


Oct 23: Note #1 — This week’s reading is Chapter 7 in the textbook.  To complement one of the example programs in this chapter, we present the following programming challenge:

 

Go to the web site for the course textbook and download the example programs (if you haven’t already done so) and install them on your system.  In Chapter 7, there is a program called Intname.java.  Compile and execute it.  Make a copy of the program and name the new version Intname2.java.  Modify the digitName(),  teenName(), and tensName() methods to remove the series of if/else statements.  Place all the integer names in a single string and use the integer argument passed to the method to retrieve and return the appropriate integer name — a substring — from the string.

(Solution: Intname2.java )


Oct 21: Note #1 — For Monday… Please begin working on your implementation of the MyDate class.  The effort invested is well worth it, as you will be presented with a similar API implementation task on Test #2.  The API for MyDate is found on the course web site.  Click on “Tests”, then click on ”Test 2”.  For Monday, try at least to write the constructors and the toString() method.  Include a self-test main() method to exercise the class at each stage of implementation.  This will facilitate the combined efforts of implementing and debugging.


Oct 20: Note #2 — We now know how to write custom utility methods.  Let’s put this knowledge to work to improve an aspect of our example programs that we’ve side-stepped until now: input validation.  In many of our example programs, we assumed that the user was “well behaved”.  If our program requested a certain type or range of input, we assumed the user entered such.  Here’s a simple programming challenge on this topic.  The main intention is to acquire practice in writing custom static methods.

 

Write a program called InputInteger (and YInputInteger using the york package).  Your program should prompt the user to input an integer.  If the user enters an integer, print the value on the console and exit.  If the user does not enter an integer, reissue the prompt and repeat.  Here’s a sample dialogue: (Explanatory comments appear on the right.)

 

PROMPT>java InputInteger             

Enter an integer:                 (blank line)

Enter an integer: -               (only a minus sign entered)

Enter an integer: ninety nine     (alpha characters not allowed)

Enter an integer: -ninety nine    (sorry! try again)

Enter an integer:    99           (leading spaces not allowed)

Enter an integer: 99 98 97        (no spaces allowed)

Enter an integer: 99              (finally!)

You entered 99 (Thanks!)

 

A variety of incorrect responses are shown.  Your task is to write and use a static method called isValidInteger() that receives a reference to a String as an argument, and returns a boolean result: true if the string represents an integer, false otherwise.  To help you get started, an outline of the solution is shown below with the critical parts missing:

 

public class InputInteger

{

   public static void main(String[] str)

   {

      /** complete, as necessary **/

   }

 

   public static boolean isValidInteger(String str)

   {

      /** complete, as necessary **/

   }

}

 

(Solution: InputInteger.java)


Oct 20: Note #1 — Now that we’ve written and debugged the SimpleStringTokenizer class, we might want to “publish it”; that is make it available to other Java programmers.   Although we don’t want to give out our source code, we do want to provide documentation to facilitate the use of the class by others.  So, here’s a programming challenge for Monday.  The main intention is the acquire experience writing javadoc comments, and also to put into practice the idea of writing a self-test main() method for custom classes.

 

Put the SimpleStringTokeninzer source file in a new sub-directory called custom off of your working directly.  Change the source file in two ways.  First, add a simple self-test main() method, along the lines of that demonstrated earlier for the BankAccount class.  Second, edit SimpleStringTokenizer.java and add appropriate javadoc comments before the class and before each method in the class.  Process the file with javadoc and view the results from you favorite browser.

(Solution: SimpleStringTokenizer.java | SimpleStringTokenizer.html |


Oct 18: Note #2 — If you invested the time necessary to write the SimpleStringTokenizer class and the ExtractWords2 program that uses the class, congratulations.  This was time well invested. 

 

There is, in fact, a class in the java.util package that is very similar to our SimpleStringTokenizer class.  It’s called StringTokenizer.  The constructor and two instance methods we wrote also exist in the StringTokenizer class.  In fact, the SimpleStringTokenizer problem was modeled on Java’s StringTokenizer class.  StringTokenizer has a few added few features, such as the ability to control the characters that delimit tokens.  This might be useful, for example, in decomposing email addresses or file pathnames into their constituent parts.

 

Take a few minutes to peruse the Java API on the StringTokenizer class (look in java.util), just to get a feel for its design.  Here is a version of the ExtractWords program that uses Java’s StringTokenizer class: ExtractWords3.java | YExtractWords3.java.  See also the notes below called “String Tokenizer Class”.


Oct 18: Note #1 — "A class is a class is a class!"  Or is it?  From our limited exposure to Java, it appears there are a few different types of classes: classes as 'factories' for objects (e.g., String), classes as repositories for static methods (e.g., Math), and classes as application programs (e.g., Hello).  Do you agree?  Let's explore this idea. 

 

On the one hand we write Java 'programs'.  Yes, they are programs in the traditional sense; however, our Java programs are also ‘classes’ because they begin with a line like this:

 

public class Hello

 

We 'execute' the Hello 'program' as follows:

 

java Hello

 

and the result is a message on the console:

 

Hello, world

 

or something similar.

 

On the other hand, in many of our programs we instantiate and manipulate objects of classes.  Examples include the String class and the Random class.  Since the String and Random classes were written by programmers at Sun Microsystems, the source code is not available for us to inspect.  However, it seems reasonable that the definition of the String would begin similarly:

 

public class String

 

We have seen the source code for a few classes of this type.  Examples include the Equation class in Lab #4 and BankAccount in Chapter 3 of Horstmann.  Indeed, the definition of these classes begins as expected, for example

 

public class BankAccount

 

So, BankAccount and Hello are both classes.  BankAccount is a factory for objects — BankAccount objects — and Hello is an application program.  The purpose of this note is to illustrate the 'common ground' in these two apparently different kinds of classes.  Let’s focus on the BankAccount class.  Here's a ten-dollar question:

 

Can we 'execute' the BankAccount class?

 

You might be tempted to ask… Why would we? Afterall, BankAccount is a class that defines the fields and methods for BankAccount objects.  Why would be want to 'execute' BankAccount, right?  Maybe we wouldn't.  But we do want to explore this question to shed some light on the common ground between classes as factories for objects and classes as application programs. 

 

We can try to execute the BankAccount class as follows:

 

PROMPT>java BankAccount

 

If we do, we'll be greeted with the following message:

 

Exception in thread "main" java.lang.NoSuchMethodError: main

 

We can't execute the BankAccount class because it does not contain a main() method.  Of course all our Java 'programs' have a method called main().  The signature always appears as follows:

 

public static void main(String[] args)

 

OK, that's fine.  But 'could we' execute BankAccount if we added a main() method?  The answer is 'yes'. Although this practice is not demonstrated in Horstmann or in the Lab Handbook, it is, in fact, a practice recommended by the designers of the Java language.  The idea is to include a main() method in all classes as a simple “self-test” of the class.  This can be useful, for example, in debugging the class as methods are written.  That's a neat idea, don't you think?

 

The practice in the course text and in the lab handbook is to use a separate program to test a class.  So, the text presents a program called BankAccountTest to test the BankAccount class.  In the 1020 Lab Handbook, there is a program called Lab4 to test the Equation class.  There is nothing wrong with this approach, but let’s explore the idea of including a main() method in a class that we wouldn’t normally think of as a ‘program’.  Let’s use BankAccount as an example.

 

Click here to view or download a new version of BankAccount.java.  This version is identical to that in Horstmann (see p. 114-115) except one additional method has been added: main().  So, this version of BankAccount can be executed.  Here's a sample dialogue:

 

PROMPT>javac BankAccount.java     (first, it must be compiled)

PROMPT>java BankAccount

==========================

Test the BankAccount class

==========================

 

*** Test the constructor ***

Create a bank account with $10.00... (done)

 

*** Test the getBalance() method ***

Balance: $10.0

 

*** Test the deposit() method ***

Deposit $1.55... (done)

Balance: $11.55

 

*** Test the withdraw() method ***

Withdraw $3.98... (done)

Balance: $7.57

 

*** TEST COMPLETE ***

 

Have a look at the code for the main() method in BankAccount.java. You’ll see that main() systematically tests the BankAccount class.  It begins by instantiating a BankAccount object using the constructor.  Then it tests the getBalance(), deposit(), and withdraw() methods.  These methods are pretty simple, so the benefits of including a main() method are perhaps not apparent.  However, if the class included any methods that involve number crunching or other complex code, then the benefits of including a main() method surface.  Debugging services, such as program traces (see the notes “Debugging” below) can be added to or removed from the main() method on an as-needed basis until a method is debugged and working.  This is an excellent way to write a custom class, because, for example, the work proceeds with just one source file, rather than two.  This streamlines the design and testing process considerably.

 

The idea of using a main() method to help in the design, testing, and debugging of a class is great.  But, additionally, including a main() method in BankAccount validates our opening point:: A class is a class is a class!


Oct 17: Note #2 — Also for Wednesday… read (a) the notes “javadoc” posted at the bottom of this web page, (b) Productivity Hint 7.1 on page 293 in the text, and (c) page 6 in Lab #5 the Lab Handbook.  These all pertain to javadoc, which we’ll discuss in class on Wednesday.


Oct 17: Note #1 — We had a pretty good discussion in class yesterday about one of the bullets under Highlights in lab #4. The bullet reads

 

·        Supply a public toString method to override the address-based default.

 

Let’s consider the Equation class as an example.  There is a toString() method in the Equation class, so we did indeed do this in Lab #4.  But let’s think further of the implications of this, as we did in class.  I’d like to encourage you to take a similar approach to this note in learning about Java.  That is, write small programs to test your understanding and to learn by trial.  I just wrote a program called Temp.java.  Here’s the source code:

 

public class Temp

{

   public static void main(String[] args)

   {

      Equation e = new Equation(1, 2, 3);

      System.out.println(e.toString());

   }

}

 

I compiled and ran this program, and received the following output:

 

1.0x^2 + 2.0x + 3.0  =  0

 

If you did Lab #4, then you know that this output is exactly as expected.  One of the first points in our discussion yesterday was noting that the toString() method isn’t needed in the print statement above.  If you print an object (by passing its reference to the println() method), then toString()is automatically invoked to convert the object to a printable string.  So, if I change the print statement above to

 

System.out.println(e);

 

the same output is generated.  That’s fine.  We already know this.  But, what if the Equation class did not have a toString() method?  This is exactly the case with the BankAccount class given in the text (see p. 114-115).  The definition of the BankAccount class does not include a toString() method.  As inferred in the bullet above, the “address-based default” will be used if a BankAccount object is printed.  What is the “addressed-based default”?   Before we discuss this, let’s do it. 

 

Here’s what I did, and I encourage you to do the same…  I edited the source code for my Equation class and put comment markers around the definition of the toString() class.  In other words, I put  /* before the method definition and */ after.  Then I recompiled Equation.java.  Now, my Equation class does not have a toString() method.  I re-ran Temp and received the following output:

 

Equation@73edb769

 

Yikes!  The string above contains the name of the class (Equation), followed by the commercial at sign (@) followed by the hash code of the instance (73db760).  This is pretty cryptic and of no use to us.  What is important is to understand how this string representation of our Equation object was generated.  It was generated by the toString() method of the Object class!  This is the “address-based default” alluded to in the bullet.  (A hash code is similar to an address, hence the term “address-based”.) 

 

The Object class in Java is the root of the class hierarchy.  All classes extend Object — they are subclasses of the Object class.  Because of inheritance, all the methods of the Object class are automatically methods of subclasses of the Object class.  So, all methods of the Object class are automatically methods of classes like Equation or BankAccount.

 

How does one learn what methods are defined in the Object class?  We explored this in class yesterday.  You look in the Java API.  The Object class is in the java.lang package.  Look there and you’ll get the complete scoop on the Object class, including a description of its methods.  You should take a few minutes to do this, if you haven’t already.  Do the same for the String class and Math class, which are also part of the java.lang package.

 

If a class provides its own toString() method, this will be used when an object of the class is converted to a string, for example, by printing the object.  This definition is said to override the definition in the class’s superclass. If a class does not provide its own toString() method, then the toString() method of the superclass — Object — is used, and you can see the result above.  Obviously, printing the hash code isn’t much use to us.  If you read the description of the toString() method in the API for the Object class, here is what you’ll find:

 

In general, the toString() method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

 

This is the same recommendation as found in the bullet!

 

One method in the Object class you should read about is the equals() method.  The explanation is a bit complicated, but we have already explored this.  We wrote an equals() method for the Equation class to override the Object class’s equals() method.  See step 4 on page 4 in Lab #4.

 

For further discussion on this topic, see the notes below “Organization of Java”, “Defining Classes”, and “Extending Classes”. 


Oct 16: Note #2 — for Wednesday… work on the SimpleStringTokenizer class and the ExtractWords2 program.  See Oct 13: Note #1 for details.


Oct 16: Note #1 — Hopefully you found time between studying for Test #1 and working on your labs to write the program CharCodeChart3.  If you didn’t, you should at least review what we did.  Here’s a summary.  We wrote a simple static method called myRepeat() that mimics the operation of the repeat() method in the york package.  Of course, we could have just used the york package’s repeat() method, but the goal was to begin thinking about writing our own custom methods.  So, CharCodeChart3 includes a custom method called myRepeat().  Have a look at the source code if you haven’t already (CharCodeChart3.java). 

 

Rather than give you yet-another programming challenge, the program presented here is provided for discussion purposes only.  The program is called Marquee2.  Functionally, it’s identical to Marquee, which you wrote last week.  Marquee2 is a follow on to CharCodeChart3.  CharCodeChart3 contains the definition of a static method called myRepeat().  Since it is 'static', it is invoked through the class, rather than through an instance of the class (as is the case for instance methods).

 

Just as we call static methods of the Math class through the class, e.g.,

 

double x = Math.sqrt(25);

 

we can call a static method of the CharCodeChart2 class:

 

String s = CharCodeChart3.myRepeat(50, "-");

 

For the statement above to work, the class CharCodeChart3 must be reachable by the compiler.  Here’s the source code for Marquee2: Marquee2.java.  The important point is this: Marquee2 doesn’t not contain the source code for myRepeat(): It simply uses the myRepeat() method (which is contained in the CharCodeChart3 class).

 

Don’t you think it’s a bit odd to reference CharCodeChart3 just to use myRepeat() in another program?  After all, what does a program that displays a Unicode chart have to do with general-purpose utility methods!  You’re right, it is a bit odd (and the practice is not recommended).  The purpose of Marquee2 is simply to demonstrate the 'reuse' of static methods that we define.  In practice, static methods that are candidates for reuse are placed in a general-purpose class.  For example, the myRepeat() method and other custom-designed utility methods could be placed inside a class called MyUtil.  MyUtil.java might look like this:

 

public class MyUtil

{

   public static String myRepeat(int count, char c)

   {

     String s = "";

     for (int i = 0; i < count; ++i)

        s += c;

     return s;

   }

 

   /** other static utility methods **/

}

 

MyUtil, like the Math class in java.lang, would exist purely as a repository for static methods.  Like the Math class, MyUtil “objects” would not be instantiated.  Methods in MyUtil are invoked “on the class”, not on objects of the class, for example:

 

String s = MyUtil.myRepeat(15, "*");

 

This makes more sense.  MyUtil is a custom class holding a variety of static utility methods that are available for use in other Java programs.  Can you think of other common formatting tasks that might be implemented in static methods and placed in MyUtil?  If so, then get to it!


Oct 13: Note #1 — Our ExtractWords program included some services that might be useful in other programs.  Having successfully laboured over the coding and debugging of these services, it seems reasonable to consolidate them in a convenient form so that other programmers can benefit from our previous efforts — without 're-inventing to the wheel', so to speak.  To this end, we are confronted with the following programming challenge.  It involves writing a custom class, along the lines of  Equation in Lab #4 or BankAccount in Chapter 3 of Horstmann. The solution will be taken up in class on Wednesday.  Try to put together your own solution before then.

 

Write a Java class called SimpleStringTokenizer that implements the useful services from ExtractWords.  These include the following:

 

1.  The ability to receive a line of text as a string and prepare for extracting words from it.  We'll need a 'constructor' method to implement this service.  Here’s the signature:

 

public SimpleStringTokenizer(String line)

 

2.  The ability to extract the next word — a 'token' — from the string.  We'll need a nextToken() method for this service.  Here’s the signature:

 

public String nextToken()

 

3.  The ability to determine if there are any more words to be extracted from the string.  We'll need a hasMoreTokens() method for this service.  Here’s the signature:

 

public boolean hasMoreTokens() 

 

One detail we would rather not confront again is managing an index to assist in scanning through the string.  Things like leading and trailing spaces in the string or multiple spaces between words were a nuisance to handle and we had a few tricky bugs to solve before finally getting ExtractWords to work.  Our SimpleStringTokenizer class will deal with these details internally, thus reducing the burden on a programmer using our custom class. So, the following is added to our list:

 

4.  Manage details of processing the string.  We'll use two 'private' variables for this purpose: s, a String that holds the string to be tokenized, and i, an int used as an index into s as tokens are extracted.  The declarations are as follows: 

 

private int i;

private String s;

 

Once your SimpleStringTokenizer class is written, it must be tested.  Write a program called ExtractWords2 (and YExtractWords2 using the york package) that uses a SimpleStringTokenizer object and its associated methods to perfrom the same task as ExtractWords.

(Solution: SimpleStringTokenizer.java | ExtractWords2.java | YExtractWords2.java )


Oct 12: Note #3 — In the Lab Handbook, Appendix B, page 2, the following expressions are given for converting strings to numbers: (Assume s is a String object representing a number of the appropriate type)

 

Byte.valueOf(s).byteValue()

Short.valueOf(s).shortValue()

Integer.valueOf(s).intValue()

Long.valueOf(s).longValue()

Float.valueOf(s).floatValue()

Double.valueOf(s).doubleValue()

 

Note that the following expressions have the same effect:

 

Byte.parseByte(s)

Short.parseShort(s)

Integer.parseInt(s)

Long.parseLong(s)

Float.parseFloat(s)

Double.parseDouble(s)

 

The first group of expressions are used in the Lab Handbook.  The second group are used in Horstmann and in our example programs.  Note that Byte, Short, Integer, Long, Float, and Double are classes in the java.lang package.  They are known as wrapper classes, because they serve to “wrap” a primitive data type into an object.  For more details, see the Java API or the notes “Wrapper Classes” below.


Oct 12: Note #2 — Errata: In the notes “Program Flow – Loops”, just after Figure 2, the description should read, “Since x was just initialzed to zero, the result is true…”.  The PDF file has been updated.  Thanks to Melanie Lou for pointing this out.


Oct 12: Note #1 — This week’s reading is Chapter 6 in Horstmann.  There is a code fragment on page 239 that is worth thinking about.  Horstmann points out that in reading input, “the challenge is to detect the end of input”.  He gives a short example in the middle of the page which is repeated below with a minor change to illustrate use of the york package:

 

boolean done = false;

while (!done)

{ 

   String line = York.readLine();

   if (line == null)

      done = true;

   else

   {

      /** process data **/

   }

}

   

This is exactly the same as

 

String line;

while ((line = York.readLine()) != null)

{

   /** process data **/

}

 

The approach above is much simpler, don’t you think?  The trick is to use assignment within the relational test of the while statement.  Assignment has the lowest priority of Java’s operators, so an extra set of parentheses is needed to ensure the assignment takes place before the relational test != null.  Here’s how the while expression above works: Normally, a line of characters is read from the keyboard via readLine() and is converted to a String object.  readLine() returns a reference to the object and this is assigned to the object variable line.  This occurs even if a blank line is input.  For a blank line, line is still assigned a reference to a String object.  It just happens that the String object contains an empty string.   However, if an end-of-file condition occurred, the value returned by readLine() is null.  This is a legitimate value for an object variable.  It simply means that the object variable does not refer to any object.   So, as long as lines of text are read (including blank lines), the relational test yields true and the statement block labelled “process data” executes.  As soon as an end-of-file condition occurs, the relational test yields false and the statement block is skipped.

 

The “end-of-file” condition is generated in one of two ways.  If input is from a disk file, it is automatically generated by the operating system after the last line in the file is read.  If input is from the keyboard, the end-of-file condition is manually generated by the user.  This is accomplished by typing a line beginning with either Ctrl-z on Windows or Ctrl-d on unix.


Oct 11: Note #3 — Please attempt to solve the programming challenge posted on Oct 8 — ExtractWords.  We’ll look at a solution in Friday’s class.


Oct 11: Note #2 — Here is a simple programming challenge which we’ll also take up in Friday’s class.  By way of background, in this week’s lab — Lab #4 — we will write a class called Equation.  In the Chapter 3 of the text, we saw the blow-by-blow design of a class called BankAccount.  In both cases, several methods were written.  These are all “instance methods”, because they are invoked on an instance of the class.  The other type of method is a “static method”.  We have used static methods extensively in our Java travels, for example,  Math.sqrt(25) or York.repeat(25, ‘-‘).  Plus, we have written many examples of the main() method, which is also a static method.  In this programming challenge we will write a simple static method.  Here’s the challenge:

 

Make a copy of the program CharCodeChart2.java and name it CharCodeChart3.java.  Our task for CharCodeChart3.java is to simplify the awkward code that draws lines in the chart.  If you compare CharCodeChart2.java with YCharCodeChart2.java, you’ll get the general idea.  Include in CharCodeChart3 the design and use of static method called myRepeat() that mimics the operation of the repeat() method in the york package.  To get you started, here is an outline of the program, with the critical parts missing:

 

public class CharCodeChart3

{

   public static void main(String[] args)

   {

      /** copy code from CharCodeChart2             **/

      /** simplify line drawing by using myRepeat() **/

   }

 

   public static String myRepeat(int count, char c)

   {

      /** complete, as necessary **/

   }

}

(Solution: CharCodeChart3.java )


Oct 11: Note #1 — Here are the “character code” programs demonstrated in today’s class: CharCodeChart.java | YCharCodeChart.java | CharCodeChart2.java | YCharCodeChart2.java )


Oct 9: For your information, CountLetters2.java and YCountLetters2.java are now posted.  These programs include one very small but interesting change from the CountLetters program demonstrated in Friday’s class.  We’ll talk about this in class on Wednesday.


Oct 8: The following programming challenge will be taken up in class on Friday.  Try to put together your own solution before then.  This problem will serve as an introduction to several other programs, where we demonstrate defining our own classes, using new classes in the Java API, etc.  So, it’s important not to get behind.

 

Write a Java program to extract words from lines of text read from the keyboard (or from a file using input redirection).  Print the words on the console, one per line.  For the purpose of this program, a word is any sequence of characters delimited by spaces or an end of line.  Make sure your solution can handle leading or trailing spaces in a line, as well as multiple spaces between words.  Write two versions of the program: ExtractWords using ‘straight’ Java and YExtractWords using the york package  Here is a sample dialogue showing input redirection:

 

     PROMPT>type temp.txt         (on unix, use cat instead of type)

     hello, there

     good bye!

     PROMPT>java ExtractWords < temp.txt

     hello,

     there

     good

     bye!

     PROMPT>

 

To help you get started, here is an outline of the solution with the critical details missing:

 

import york.*;

public class YExtractWords

{

   public static void main(String[] args)

   {

      String s;

      while ((s = York.readLine()) != null)

      {

         /** complete, as necessary **/

      }

   }

}

 

Don’t get too fancy!   Restrict your solution to int, char, and String and use only the length() and charAt() methods of the String class.  Your part of the solution should take about ten lines of code.

(Solution: ExtractWords.java | YExtractWords.java )

 


Oct 7: A new PDF file titled “Precedence of Operators” has just been added below under “Notes”.


Oct 7: How many days, hours, minutes, and seconds remain until Test #1?  To find out, download, compile, and execute the following program: TimeToTest.java


 Oct 6: Here is the demo program presented in today’s class: DemoRandom.java | YDemoRandom.java


Oct 5: Here are a few additional programming challenges.  These are all simple programs that can be written in just a few lines of Java code.  It’s extremely important to quickly hone your programming skills on the basic constructs of the Java language.  We’ll look at solutions either tomorrow or next Wednesday, as indicated.

 

#1     (for tomorrow) - Write a program that draws a rectangle on the console.  Use asterisks (‘*’)  to create the rectangle.  Your program should prompt the user to enter the width and height of the rectangle.  Specify a range, but don’t worry about input validation for the moment.  Write two versions of the program: MakeRectangle using ‘straight’ Java, and YMakeRectangle using the york package.  Here is a sample dialogue:

 

PROMPT>java MakeRectangle

Enter width of rectangle (1-60): 33

Enter height of rectangle (1-40): 5

*********************************

*                               *

*                               *

*                               *

*********************************

PROMPT>

 

Hint: You’ll need a “loop within a loop”.  Although you can solve this problem using any of the three loop constructs (while, do/while, for), for loops are probably you’re best bet.

(Solution: MakeRectangle.java | YMakeRectangle.java )

 

#2     (for Wednesday) Write a program that prints the letters a-z and A-Z and their corresponding numeric code.  Name the program LetterCodes.  Create the output in two columns, as shown in the following abbreviated dialogue:

 

PROMPT>java LetterCodes

A 65   a 97

B 66   b 98

C 67   c 99

D 68   d 100

...

Z 90   z 122

PROMPT>

 

Your solution should declare and use only one variable — a char.  Note: This program can be written in just one Java statement.

(Solution: LetterCodes.java )

 

#3        (for Wednesday) Write a program to create a marquee.  Your program should prompt the user to enter an important message and then print the message with a fancy border on the console.  Write two versions of the program: Marquee using ‘straight’ Java and YMarquee using the york package.  Here is a sample dialogue:

 

PROMPT>java Marquee

Enter an important message...

U. of T. Blues vs. York Yeomen, Today 4:00 p.m.

***************************************************

*                                                 *

* U. of T. Blues vs. York Yeomen, Today 4:00 p.m. *

*                                                 *

***************************************************

PROMPT>

 

(Solution: Marquee.java | YMarquee.java )

 

#4     (for Wednesday) Write a program that counts the occurrences of the string “the” in a line of text read from the keyboard.  Output an appropriate message to the console.  Write two versions of the program: CountThe using ‘straight’ Java and YCountThe using the york package.  Here is a sample dialogue:

 

PROMPT>java CountThe

Enter a line of text

the other side of the mountain

3 occurrence(s) of ‘the’

PROMPT>

 

(Solution: CountThe.java | YCountThe.java )


Oct 4: Here’s a simple programming challenge.  Try to do this for Friday’s class.

 

Write a program that reads lines from the keyboard until an eof (end of file) is input (^z on Windows, ^d on unix).  Count the number of letters entered (a-z, A-Z) and output an appropriate message to the console.  Write two versions of the program: CountLetters using ‘straight’ Java, and YCountLetters using the york package.  (Warning: If you are working on a Windows system, your program should print a blank line before printing your message.  I’ll demonstrate why this is necessary in class.)

(Solution: CountLetters.java | YCountLetters.java )


Oct 4: If you need assistance with Lab #3 — beyond what is in the Lab Handbook — make sure you consult the api of the york package and read the notes provided for YorkReader and YorkWriter.  The notes below, “Stream Classes and File I/O”, are also relevant; however, they do not reference the york package, which you must use for this lab.  The demo programs in the notes are given both using ‘straight’ Java and using the york package, so these should prove helpful.


Oct 4: To follow up on a question in Monday’s class, re character codes, see CharCodes.java


Oct 2:  Here’s a simple programming challenge.  We’ll look at a solution to this in Wednesday’s class; so, try to work on it before then.  Remember, you can’t learn to program by reading about it!

 

Write a Java program that verifies that an integer is in a desired range.  The program should begin by outputting a prompt requesting the user to enter a number in a specified range (e.g., -5 to +5).  Input and verify the number.  If it is in the specified range, output "Thanks!"  Otherwise output "Out of range!"  Name the program EnterNumber.

(Solution: EnterNumber.java | YEnterNumber.java)


Sept 29: Errata:  The program JavaIsFun prints a message 6 times, not 5 times, as stated in the notes.  The notes (ProgramFlow – Loops) and program have been updated.  The message now prints five (5) times!


Sept 28: To follow up on our class discussion on equals() vs ==, see the demo program StartsWithZed.java.