April 29, 2009 Tests from yester year


April 27, 2009 End of course survey


April 27, 2009 MTDemo.java


April 24, 2009 I think I am going to cry

 

Updated version

XIMU.java


Movie and Theater

Theater.class


Movie.java

    On your honor do not look at the file until after you complete the quiz.


    The final homework assignment is to write three of its methods. The total amount of code you need to write is about twelve lines.

First righteous praise

I saw a bunch of code before class, during class, and after class.

I have been impressed with the quality of your solutions. If you are not yet done, review my new notes and the previous notes. Make sure you read carefully.

Now gotchas, help, and advice

There are two IM.java methods for determining folder names: getXimuLocation() and getXimuPage().

  • If you are trying to read who are your friends or modify your status, then the folder for that file must come from your home directory ximu subfolder. For example, to get a Connection to your friends file:
    	String myXimuFolder = this.getXimuLocation();
    	Connection c = new Connection( myXimuFolder, "friends" );
    

  • If you want to read a message from some person, then the folder in which it is stored does not lie on your computer -- it lies out on the web. To get to that folder, you need to use getXimuPage(). For example, suppose the value of the string me is your used id and the value of string buddy is the id of the person whose message you want, then the following sets up a Connection to that file.
    	String myBuddyXimuFolder = this.getXimuPage( buddy );
    	Connection c = new Connection( myBuddyXimuFolder, me );
    

To tests two strings if they look the same, uses the equals() method. For example, to see performs some action if string word has the value "here", then the code would be:

	if ( word.equals( "here" ) {
		// person is logged on ...

Some people have never run the Setup program or never done it correctly. To run it correctly:

  • You must be logged on to the Home Directory Service. Use the Home Directory iconon your desktop and connect to the service. If you do not know your Eservices password, you can reset it by go here and then log on.


  • Redownload the Setup.java. Pay attention to where you put it.

  • Open JCreator or DrJava and open the file you just downloaded (pay attention that you grab the one from the correct folder).

  • Run the program. It should indicate success when done. If it gives an error message, you are most likely not connected to the home directory service. If you cannot figure out the error, contact the teaching assistants.

Some people have more than one version of IM.java, ConsoleIM.java, and XIMU.java on their machines. Mismatches then occur when the programs are run and you get et errors even though your IM.java is okay. To make sure this is not happening to you.

  • First close JCreator or DrJava, then reopen the one of the two that you use.

  • Open IM.java. Find out where you are storing it (i.e, what folder is it in).

  • Redownload Window.java, ConsoleIM.java, and XIMU.java. Make sure you place them in the same folder as your IM.java.

  • Open Window.java, ConsoleIM.java, and XIMU.java. First compile Window.java. Next compile ConsoleIM.java. Next compile XIMU.java. These steps should put the files in sync.

If you run XIMU.java and a window pops up with a single button, your files are out of sync and perform the action list suggested above.

Whenever you make a change to IM.java, recompile it, before running ConsoleIM.java or XIMU.java.

If the folder for a Connection is not a web folder, then you can use that Connection to help you print to the file that the Connection represents. You can do so because every Connection has a behavior method getWriter().

The getWriter() method for a Connection returns a PrintStream object. Every PrintStream object has methods print() and println(). When a PrintStream object uses it print() and println() methods it updates the output source.

If a PrintSteam object is System.out, then the print() and println() methods update your desktop. If the PrintSteam object is tied to a file, then those methods update the file. For example, suppose the string variable message has the text you want to display and Connection variable c is the Connection object for the file whose contents are to be updated, then the following code causes the file to be modified.

	PrintStream output = c.getWriter();
	output.println( message );

It may be that the other IM.java methods that you were responsible for writing are preventing your getMessage() and sendMessage() from working. Below are the two methods most previously required. The other two are posted further below.

                            


April 23, 2009 Tomorrow is class picture day!

 

Updated version

ConsoleIM.java


Movie and Theater

Remember you were asked to thing about for tomorrow what attributes constructors, and behaviors would be appropriate for a Movie class concerned with keeping track for a movie at what theaters it is playing, and for a Theater class that would be keeping track of what movies it is showing.

IM

The two methods currently under consideration are sendMessage() and getMessage().

    void sendMessage( String person, String contents ): sets the current message for person to be contents

    • If the person is not an online friend, then there is nothing that needs to be done.
    • Otherwise,
      • We need to determine the ximu folder.
      • The easiest way for us to write a message is to create a Connection object. The message is to suppose to be written in the ximu folder in a file whose name is given by person.
      • A Connection object provides as one of its behaviors a message method getWriter(). The method returns a PrintStream object. Output sent to the PrintStream object will be directed by Java to the file being represented by the Connection object.
      • Use the PrintStream object to print the contents to the file.

    String getMessage( String person ): returns the current message from person

    • If the person is not an online friend, then there is nothing that needs to be done other than return null.
    • Otherwise,
      • We need to determine the ximu page folder of the person.
      • The easiest way for us to get the message is to create a Connection object. The message is to suppose to be read in the person's ximu page folder in a file whose name is name of the user (FYI: method whoami() returns the name of the user.
      • A Connection object provides as one of its behaviors a message method getScanner(). The method returns a Scanner object. Input read from Scanner object will be gotten from the file being represened by the Connection object.
      • Get the contents of the message by reading it line by line from the input gotten from the Scanner. Concatenate the inputs together as they are read. Once there is no more input return the result of the contenations.



April 22, 2009 What a day

 

Ximu update

I sent email with working versions of isFriend() and isLoggedOn(). I did so, in case your versions of the methods are preventing your initializeFriends() and whoseLoggedOn() from working. The code looked like the following.

                            

                            

Review

A Java class allows us to define a new type of object. The intent of a Java object is to model some piece of information or real word obect.

Like real world objects, software objects have to be made. The making of a software object is called construction. Also like real word objects, a software object can have attributes and behaviors.

To support the making of objects, Java allows a software designer to specify special methods called constructors. The purpose of a constructor is to configure the attributes a new object.

A designer typically defines a default constructor. The default constructor configures the attributes of a new object to appropriate default values.

A designer also oftens defines other constructors called specific constructors. A specific constructor has information passed to it through its parameters that guide (specify) how the object is to be configured.

Constructor definitions are easy to spot with in a class definition. As a constructor is a method, its definition resembles other method definitions except in two ways.

The name of a constructor is always the same as the name of the class. The requirement seems reasonable to most. The constructor makes the object so why not name it after the class.

In addition, a constructor does not have a return type. The reason being its seems redundant. A constructor for some class by its nature always produces an object of that class so why be verbose.

The attributes of an object are specified using variables. Some software developers refer to attributes as fields. This name harkens back to how information was represented in an earlier programming languages. I for one do not use the term. An object is a more powerful and natural device and deserves a more suitable terminology.

Programmers also refer to attributes as instance variables. Although appropriate -- an object is a particular instance of its class type and the attributes are the variables that hold values that describe the instance -- the name is awkward (especially for new programmers). So I try to consistently use attributes when describing an object.

It is easy to tell whether a variable definition is defining an attribute or a local variable. Local variables are defined within methods, and attribute variables are not.

Another thing to know about attribute variables is that even before a constructor configures a new object, Java has assigned values to the attributes. Numeric attributes are preset to 0, logical attributes are preset to false, and all other attributes are preset to null.

The members of a class are defined one after another within the curly braces demarking the definition. A member can be an attribute, a constuctor, or a method describing an object behavior.

A method describing an object behavior is often called a message method. It has this name because using the method is essentially sending a message to the object to carry out the behavior.

A message method is different than the service methods we considered earlier. A service method performs an action independent of a particular object. A service method is often called class method -- the method belongs to the class itself rather than being associated with an object.

For example, throughs its Math library Java provides a service method tan() for determining tangents. The method invocation Math.tan( 1 ) tells the Math library to compute and return the tangent for the angle whose degree is 1 radian.

As an example of an object behavior, the message method contains() from ArrayList queries a list whether it contains a particular value. If list was an ArrayList object, then the invocation list.contains( "mst3k" ) makes sense -- it is asking whether "mst3k" in particular is a value of list. The invocation ArrayList.contains( "mst3k" ) is illegal, does not compile, and does not make sense -- there is no list specified for checking whether "mst3k" is one of its values.

You can tell from the beginning of the method's definition whether it is a message method or a class method. A class method must use the keyword static; a message method is not allowed used to the keyword static.

Methods we intend for users of the class to use are given the label public; methods intended for just internal use by the class can be given the label private. A private method cannot be accessed outside of its class.

Attributes are often made private for safe keeping. Users of the class are made use to accessor and mutator methods to access and manipulate the attribute. We call this information hiding. The accessor and mutator methods can be written to ensure that the object is always treated sensibly. For example, an object to represent rational numbers could make sure that its mutators never allow the denominator to become zero.

Accessor methods are colloquially called getter methods -- they give the user access to an attribute value. Mutator methods are analogouslly called setter methods -- they give the user the ability to set an attribute value.

For commonality, Java ensures that every object has three behaviors. They are the clone() method that returns a duplicate of the object; the toString method that returns a text representation of the object; and the equals() method that tests whether the object passed to the method matches the object being sent the equals message.

I and others, as well, call methods clone(), toString(), and equals(), "the gang of three". If a class designer does not define one of the gang, then the class inherits one. The inherited methods are typically unsuitable, so a good class designer explicitly provides them.

Constructor and message definitions have access variable named this. Consider the this variable to be one automatically set by Java. For a constructor, the value of the this variable is the new object itself. For a message method, the value of the this variable is the object being sent the message.

To consider a particular class on which to consider for the review, we use the simple class Article for representing the title and author of an article.

01. public class Article {  
02. private String title; // attribute
03. private String author; // attribute
04. 05. public Article() { // default constructor 06. this.setTitle( "" ); 07. this.setAuthor( "" ); 08. } 09. 10. public Article( String t, String a ) { // specific constructor 11. this.setTitle( t ); 12. this.setAuthor( s ); 13. } 14. 15. public void setTitle( String t ) { // mutator 16. this.title = t; 17. } 18. 19. public void setAuthor( String a ) { // mutator 20. this.author = a; 21. 22. } 23. 24. public String getTitle( ) { // accessor 25. return this.title; 26. } 27. 28. public String getAuthor( ) { // accessor 29. return this.author; 30. } 31. 32. public String toString( ) { // gang member 33. String t = this.getTitle(); 34. String a = this.getAuthor(); 35. String representation = "Article( " + t + ", " + a + " )"; 36. return representation; 37. } 38. 39. public boolean equals( Object v ) { // gang member 40. if ( ! ( v instanceof Article ) ) { 41. return false; 42, } 43. else { 44. Article that = (Article) v; 45. String t1 = this.getTitle(); 46. String a1 = this.getAuthor(); 47. String t2 = that.getTitle(); 48. String a2 = that.getAuthor(); 49. boolean compare = ( t1.equals( t2 ) && a1.equals( a2 ) ); 50. return compare; 51. } 52. } 53. 54. public Object clone( ) { // gang member 55. String t = this.getTitle(); 56. String a = this.getAuthor(); 57. Article duplicate = new Article( t, a ); 58. return duplicate; 59. } 60. }

IM

The two methods currently under consideration are initializeFriends() and updateWhoseOnline().

initializeFriends(): set up the list of friends

  • The friends are suppose to be kept in attribute friends, where friends is an ArrayList<String>.
  • The ArrayList<String> default constructor will set up an empty list.
  • The contents of the user's "friends" file need to be read. Each word in the file corresponds to a friend to be added to the list.
    • A Connection object is a handy way to get a hold of a Scanner to the file. The file "friends" is located in the user's ximu folder. IM message method getXimuLocation() can be used to get that folder's pathname
    • A loop that iterates while there are more names to read should allow the necessary processing to be accomplished.

updateWhoseOnline(): reset list of online friends

  • The friends are suppose to be kept in attribute onlineFriends, where onlineFriends is an ArrayList<String>().
  • Begin by resetting that list to the empty list.
  • Access to the list of all friends can be accomplished using IM message method getFriends().
  • For each name in the friends' list determine whether that person is online. If the person is online, then add them to the list. If the person is not online, then do not add them to the list.
  • Using the IM message method isLoggedOn() can tell you whether a particular person is online.



April 20, 2009 What did we learn today

 

Nuts and bolts

One Calculator question came up multiple times. What happens if the value of parameter n to method divide() is zero. The answer is do nothing and be silent about it (no warnings are necessary or even wanted).

After the quiz, we spent a lot of time making sure we all had the right mental model of how our instant messenger makes use of local folders and files and use of web folders and pages.

Suppose your email id mst3k.

We saw that the home directory subfolder J:\public_htm\ximu and the web folder http://www.people.virginia.edu/~mst3k/ximu are two different ways to refer to the same folder.

The class IM provides two methods for getting a hold of ximu folders. If im is an IM object, then

String lx = im.getXimuLocation();

defines and sets lx to be the name of the local folder. If the user was mst3k, then lx would be "J:\ximu". And the defintion

String wx = im.getXimuPage( p );

defines and sets wx to be the name of the web folder for person named by p. If the person p was myself, then wx would be "http://www.people.virginia.edu/~jpc/ximu".

Both getXimuLocation() and getXimuPage() are already implemented for you. Sweet.

We reviewed the attributes of an IM object. One of the attributes is an ArrayList of friends. The IM getter method getFriends() gets us access to the list.

ArrayList<String> list = im.getFriends();

defines and sets list to refer to the friends by the user of the IM.

We remembered that every ArrayList object has a message method contains(). If list is an ArrayList object, then list.contains( v ) reports whether one of the elements of list has the same value as v.

We saw that class Connection can be pretty handy. Consider the statement

Connection c = new Connection( f, n );

creates a new Connection named c. Object c represents a connection to the file named by n within the folder named by f.

It got mentioned (stressed) that with a Connection object we can set up a Scanner to read from the associated file (regardless whether the file is a local file or a web page).

Scanner s = c.getScanner();

It also got mentioned that with a Connection object we can set up a PrintStream object to write to the associated file (the file must be a local file).

PrintStream out = c.getWriter();

And with that PrintStream object we can issue println() and print() instructions to put text into the file.

out.println( "here" );

IM method isFriend() has a simple implementation.

  • Get a hold of the friends list
  • Return whether the friend contains the person of interest.

IM method isLoggedOn() is also not that difficult to implement.

  • Determine whether the person is a friend (method isFriend() can help you here).
  • If the person is not a friend then
    • return null;
  • Otherwise
    • Determine the ximu web folder of the person (method getXimuPage() can help you here).
    • Try to set up a connection with the filed named "status" within that web folder.
    • If the connection is null, then the person is definitely not logged on. Otherwise, a Scanner can be gotten to read from the file. If the first word read equals "here", then the person is online; otherwise, the person is not logged on.

People asked how can we test the two IM methods due Tuesday. My suggestion modify method main() of ConsoleIM.java to try out the methods. For example, if im is and IM object, then

boolean b1 = im.isFriend( "Craig" );
System.out.println( "b1: " + b1 );

should display false as Craig was not added to anyone's friend list. The code segment

boolean b2 = im.isFriend( "jpc" );
System.out.println( "b2: " + b2 );

should display true as "jpc" was added to everyone's friend list.

The code segment

boolean b3 = im.isLoggedOn( "Craig" );
System.out.println( "b3: " + b3 );

boolean b4 = im.isFriend( "bcs8d" );
System.out.println( "b4: " + b4 );

should display false both times as Craig is not a friend and Blake always has her status set to gone.

The code segment

boolean b5 = im.isFriend( "jpc" );
System.out.println( "b5: " + b5 );

should display true as I am a friend who is always logged on. You could also test out yourself. If you are running the instant messenger then you are logged on.


April 20, 2009 May I have your attention please

 

Files of ongoing interest

Now back to our regularly scheduled show

Developing your object-oriented skills has been our focus for the last couple of weeks. The primary examples have been:

  • Cupcake: our first example was designed to get your attention. We saw through physical examples (i.e., the cupcakes I made and distributed) and through the displays of the corresponding virtual cupcakes that we constructed, that objects have their own attributes. Your cupcake is a different cupcake than your classmate's cupcake. Changes to your cupcake do not affect your classmate's cupcake and vice-versa.

  • Person: our second example was designed to keep your attention and there was again a visual component. We saw pictures of ourselves and celebrities. Our focus here was the use of default and specific constructors. Our focus was also on message methods to access, modify, and manipulate objects -- understanding getters, setters, and toString() in particular. The role and use of the this variable and access rights -- public and private were also considered. The class kept us busy.

  • Triple: with this class we started to consider object nuances and expectations. The class provides an object that can hold three positive numbers. I would call this simple class, synthetic. It allows us to consider the various components of object-oriented design and implementation, but it does not have any real use. Its primary advantage is its simplicity -- its easy to imagine a container for three numbers. You used your knowledge and acumen to complete the class. We also considered two other methods equals() and clone() that along with toString(), I informally call the gang of three. Software developers routinely expect that a class will have tailored versions of the methods. Plan on including these methods in your designs and implementations.

  • A: provides an object that can hold a single integer value. Clearly, even more synthetic than Triple -- Java already provides two integer representations: the fundamental type int and the wrapper class Integer. Its only advantage is its utter simplicity. It allows us to get a quick check on your understanding of object-oriented design and implementation.

  • AlarmClock: at this point the class is misnamed -- it only keeps the time. May be in the future, you will be able to augment the class to also keep track of an alarm time. Regardless, it was a vehicle to further practice your objected-oriented design and implementation abilities.

  • Calculator: provides a simple calculator object for basic arithmetic operations and supports standard object behaviors. You were strongly encouraged in your implementation to have your methods use the getters and setters whenever possible. Such practices typically make development and changes to a class easier.

That was then, this is now

Its now time to develop a class for something cool -- instant messenging. Something for you to show your friends and relatives how much you have learned.

Believe it or not, the instant messenger we are going to develop is relatively simple to implement. So let's begin.

The two most important features of an instant messenger are its abilities to receive and send text. To get or send a message, a network connection between your instant messenger and your friend's instant messager needs to be established.

Java provides sophisticated resources that can ensure proper and secure linkage between the instant messengers but we are not going to use them. They are a little cumbersome to use and figuring them out is not the purpose of this assignment. What I want and what you need is practice doing class design and implementation -- developing a nontrivial collection of attributes, constructors and message methods that provide the expected capabilities for some object type.

To send and get messages we are going to make use of one of the nice services that UVA provides to all members of our community -- the home directory folder. As part of the home directory client we can make some of our files readable on the world-wide-web. We are going to use that ability to put messages in a web-readable subfolder for our friends to read and get messages from their corresponding web-readable subfolder.

We have been reading web files for most of the semester so doing that is no big deal, but we have not written files. I guess that situation is my fault.

To make reading and writing files simple, I have developed a class called Connection. This class allows you to develop an object associated with either a local file or web page. The class provides a method to get a hold of a Scanner by which you can read its text. The class also provides a method that lets you get a hold of a writer that lets you display text to the file (the file has to be locally named and owned -- you cannot arbitrarily write pages to someone else web folders).

  • public Scanner getScanner(): returns a new Scanner that reads from the file name being maintained by the Connection object.

  • public PrintStream getWriter(): returns a new PrintStream that can reset the text in the name of the file being maintained by the Connection object. Like PrintStream object System.out, every PrintStream object has methods print() and println() for capturing text to the resource.

Our instant messenger class will be named IM.java. Every IM object will have four attributes:

  • String ximuFolderLocation: remembers where the user's im folder is located on the UVA home directory system. The setting of this attribute is done for you during object construction. Access to the folder name can be gotten through the already implemented getter method getXimuLocation().

  • String user: remember's the user's email id. The setting is this attribute is done for you during object construction. Access to the user name can be gotten through the already implemented getter method whoami().

  • ArrayList friends: keeps track of the user's instant messenger friends. Building the list is one of your responsbilities -- method initializeFriends(). The list can be read from the file named "friends" in the user's ximu folder. Getting a hold of a Scanner to read the file is simple using class Connection. Once built, access to the list can be gotten through the already implemented getter method getFriends(). You are also responsible for method isFriend() that determines whether the name passed as a parameter is one of the friends in the user's friend list. Reminder: every Arraylist has a method indexOf() for checking out whether something is part of the list.

  • ArrayList onlineFriends: keeps track of the user's online friends. Building the list through method updateWhoseOnline() is again one of your responsbilities. The list can be built by considering each of the user's friends and checking out whether their ximu web folder has a file "status" containing "here". Getting a Scanner for the checking out the file can be gotten using class Connection. You are also responsible for method isLoggedOn() that determines whether the name passed as a parameter is one of the user's online friends.

Besides being responsible for several of the getters and setters for the attributes being maintained by the instant messenger, you are also responsible for the two most important methods: getMessage() and sendMessage().

Surprisingly -- at least is seems surprising to me -- its easier to send a message then to get a message.

  • public void sendMessage( String person, String contents ): sends the contents as a message as long as the person is an on-line friend.
    • if the person is a friend and is online then

        Write the contents to a file name by person in the user's ximu folder. Suggestion: use class Connection to get a PrintScream that can handle the printing.

      else

        Do nothing

  • public String getMessage( String person ): returns the contents of the current message from the friend. If the person is not an on-line friend, the method returns null.
    • if the person is not an online friend then

        return null

      else if the person does not have a message

        return null

      else

        Set up a Scanner (think Connection for help) that reads from the the file whose name matches the user's name from the person's online ximu web folder.
        Set up a loop that uses the Scanner to read all of the text in the file.
        Return the text.

April 17, 2009

 

Weekend update

  • As said in class several times -- you need to be logged onto the home directory service for our instant messenger to work.
  • The windows version of the home directory service is available. Download it and install it. It should leave an icon on your desktop. Doubleclick the icon to logon to the service.

  • The Mac version of the home directory service is available. Download it and install it. After installing it, it should be available from either your applications folder or the utilities subfolder of the applications folder. Doubleclick the icon to logon to the service.

  • I redid Setup.java. I believe it will set up the ximu structure that we need. Remember you must be logged on to the home directory service before running the program.

  • As also said in class several times -- you need to become familar with

    • Connection.java: it provides functionality to make your part of the IM much easier to accomplish.

    • ConnectionTest.java: it allows you test out Connection.java

    • ConsoleIM.java: provides a console version of an instant messenger based on IM.java. To test it out, you need to have logged onto the home directory service and successfully run Setup.java. Before running it, redownload and overwrite IM.class. The IM.class file is a working version of the IM program. Be aware, when you compile IM.java it will overwrite the file with your implementation. So I suggest you play with my IM.class first. When you run ConsoleIM use as cohoon as your friend to send and get a message. ConsoleIM uses pause to allow program to be conveniently examined. When you see the prompt "IM: " give the name of your friend and the message on the same line

    • IM.class: my working version of the instant messenger.

    • IM.java: the starting point for your version of the instant messenger.

  • Expect some kind of quiz on Monday

April 17, 2009

  stopwatch

Nothing pithy

April 15, 2009

  stopwatch

I see light

April 13, 2009

  stopwatch

Time is slipping into the future

 April 10, 2009

  baseball tripleplay

Its a triple play

 April 8, 2009

  cupcake

When you need a friend

  • Person.java
    • Represents a person as an object with three attributes: an id, age, and a best-friend-forever (bff)

    • Provides a default constructor and a specific constructor, The default person has an empty name, age 0, and a null bff

    • Provides standard accessors (getters) and mutators (setters)

    • Provides opportunities to develop other methods
      • isAdult(): returns whether the person is at least 18 years old.
      • mature(): takes a single integer parameter and increases the age of the person by that amount
      • areMutualBFF(): takes a single person parameter and returns whether the people are mutual bff's
      • makeLoner(): nulls the person's bff

  • PersonFun.java

    • Puts class Person through it paces. Makes use of a HashMap that allows an easy mapping from a name to a person.

    • Several people are predefined: Paris, Nicole, Jennifer, Courtney, Angelina, Ben, Owen, Brad, Christain, and Bart

    • Once the the person of interest is specified, the possible input commands are:

      • get-age: causes the person's age to be displayed
      • get-bff: causes the person's bff to be displayed
      • get-id: causes the person's id to be displayed

      • set-age n: person's age is updated to n
      • set-bff s: person's bff is updated to s
      • set-id s: person's id is updated to s

      • mature n: person's age is updated by n years
      • is-adult: reports whether the person is an adult
      • isolate: person's bff is nulled
      • mutual s: reports whether the person and the person indicated are each other's bff

    A is for object

    • A.java
      • Represents an object keeping track of a single int value

      • Should provide a default constructor and a specific constructor, The default object has value 0 and the specific object has the value specified by the parameter

      • Should provide an accessors (getter) and mutator (setter)

      • Should also provide
        • equals(): returns whether the object has the same value as the other object
        • isPositive(): returns whether the object's value is at least 0
        • zero(): set the object's value to 0 and returns whether the people are mutual bff's
        • add(): returns a new object whose value is the sum of the object and the object given as the parameter

      AFun.java


      • When comments are removed it puts class A through it paces.

      Triple

  April 6, 2009

  cupcake

Objects

 April 3, 2009

  cupcake

Object

Wahoosa

Let's design and implement a photo manipulator. We will use as a starting point:

 April 1, 2009

  standard trophy

Test resources

 March 30, 2009

  standard trophy

Simply fabulous

  • The last month has been very fruitful. You are more adept at problem solving and now have both sufficient knowledge and practice to program in the traditional style. Coming up we will investigate object-oriented design and programming. Many system designers believe that the object-oriented approach is crucial for handling significant tasks. So look forward to our remaining time.

But what about the past

  • Our recent work has concentrated on abstraction and implementation -- looking at problems and considering what needs to be accomplished, and designing and developing methods for the necessary tasks. To successfully do so, requires familiarity with the following concepts, practices, and language components:

    • Static methods -- library-oriented methods that perform a service
    • Flow of control -- tracing of a program's execution path when a method is invoked and returns
    • Parameters -- actual and formal
    • Return -- void and and non-void, not printing, return type, and void
    • Activation record -- local and formal parameter variable storage
    • Value parameter passing -- Java formal parameter initialization process
    • Scope -- variable and parameter locality
    • Overloading -- methods with the same name but different signatures.
    • Recursion -- methods that invoked themselves to solve a problem, divide and conquer, base case, recursive case
    • Arrays -- underlying list representation, construction, default initialization, explicit initialization, for loop, elements, length field, subscripting, index, IndexOutOfBoundsException, base type, array parameters, array return type, searching, setting,
    • Multidimensional arrays -- two-dimensional arrays, row major processing, doubly nested loops.

  • Links to old tests remain available

 March 27, 2009

  Cavalier Daily March 27, 2009

Welcome class of 2013

See you in August.

Current most favored students

Please consider participating in the focus group:

  • When: Wednesday, April 8 right after class.

  • Location: 236D Olsson Hall.

  • Participation: sign up

The following files will be our focus today.

 March 25, 2009

 helmet

Focus group participation:

When: Wednesday, April 8 right after class.

Location: 236D Olsson Hall.

Participation: sign up

Put something even pithier here

 March 23, 2009

 helmet

Put something pithy here

 March 20, 2009

 array of radio telescopes

Remember

  • A link to a copy of SEAS major application form is available.

Psst

  • There will be a quiz today.

Array hurray hurray

 March 18, 2009

 monet impressionist art

Hurray for arrays 2.0

  • It was my gut feeling that most people were not prepared to come to class on Monday. I understand people are busy. UVA SEAS students are particularly busy. But we had an agreement -- if you enroll in this section, then you commit to active participation. Only together we can instill knowledge and skills that are vitally important for the technologists and leaders our University and society want you to become. So lets try again today.

As advertised and more

As promised

 

 March 17, 2009 Happy Saint Patrick's Day

  muscial annie offered a song called tomorrow

Tomorrow

Why are we here

  • Many problem solving situations require data be considered both individually and collectively. Java provides two very different ways for representing and manipulating lists.
    • Collection classes
      • Object-oriented approach
    • Arrays
      • Traditional list representation
      • Used by the collection classes in implementing their approach

Terminology

                            

array notation
array as boxes

 

 March 16, 2009 Fabulous

   mandelbrot image centered on -.1 .1 with magnification .7

Due diligence

  • The following files will be made available:


  • Please consider program ArrayExample.java What does it do? Use the worksheet to record your analysis.
  • code/ArrayExample.java

  • Please consider program ArrayPrint.java. What does it output?

    code/ArrayPrint.java

  • Please consider program ArraySet.java. What does it output? How should I modify the program to have the elements being represent be 1, 2, 5, 10, 17, ...? (This sequence is related to the sequence 0, 1, 4, 9, 16, ... ).

    code/ArraySet.java

  • How should I modify program ArrayInput.java to have the elements be initialized with values from standard input? For example, the following could be a program run:
    Enter number of words: 3
    Enter words: aa bb cc
    aa bb cc
    			

    code/ArrayInput.java

 March 13, 2009 Help yourself

 

Diligence

 March 11, 2009: If you think about it, it makes sense

 

Diligence

  • The following files will be made available:

  • Do not tell anyone else why you are doing it, but please stand at the start of class.
  • Please consider the following program. What does it output?

    code/Overload.java

  • Please consider the following program. What does it output?

    code/Nuance.java

 March 9, 2009: But wait there's more

 

Thanks

  • To the student who caught a typo in TestIs.java. I have fixed it.

Homework reminder

The Seth approach

  • If you might recall one of your classmates took a different approach to isNonZero(). Since that problem is part of the homework, I will leave it alone for now.

  • Suppose you are now told to implement a method isPositive() that returns whether its integer parameter n is a positive number.

  • Before looking for discussion on how one might do it, please spend some time yourself considering how to do it.

 March 9, 2009: Welcome back

 

Sign in right here

  • power(): returns for integer parameters x and n, x raised to the nth power.

  • doubled(): returns whether the first half of string parameter s is the same as the second half

  • deTab(): returns a new string similar to string parameter s, but with tab characters replaced by blanks.

  • isMultiple(): returns for integer parameters a and b, whether b is a factor of a

  • monospace(): returns a new string similar to string parameter s, but with sequences of blanks replaced by a single blank.

  • nonZero(): returns whether integer parameter n is non-zero

  • factorial(): returns for integer parameter n, n! -- that is

      1 * 2 * 3 * ... * n

  • zero(): returns whether integer parameter n is 0

  • inOrder(): returns whether integer parameters a and b are in sorted order

  • inOrder(): returns whether its integer parameters a, b, and c are in sorted order

  • aPallindrome(): returns whether string parameter s is the same sequence of characters forwards and backwards

  • dePunct(): returns a new string similar to string parameter s, but with punctuation characters replaced by blanks

For your viewing pleasure

For your testing pleasure

 February 27, 2009: Come fly away

 

What's going on

Consider the following program? What does it output?


Consider the following program interaction:

Enter coefficients for quadratic equation: .005 .1 20
Enter coefficients for another quadratic equation: .001 .1 20
Enter coefficients for another quadratic equation: .003 .1 15

The desired result is:



Supposed you were the software architect for this task. How might you develop such a program? How might you farm out the activities to accomplish the task?

Consider for your downloading edification:



 February 25, 2009: Blowing in the wind was another day

 

Homework update

I have the homework page to include the current assignments

Self-examination and more

The teaching assistants have suggested we try something different to improve your mastery of methods (actually they gave me a push and I chose this direction):

Suppose you have been tasked to design individual solutions for the activities listed below (i.e., methods). How would you accomplish these tasks? How might you test your solutions? Define the methods in Activity.java and the testing of the methods in TestActivity.java.

  • Produce a display of two blank lines.

  • Produce a single-line display of the integers from 1 to 30, where there is a single space following each number

  • Produce the value of the product of 121 * 99 * 71

  • Produce when given an integer representing some number of gallons, the value of its equivalent in teaspoons. FYI: there are 768 teaspoons per gallon.

  • Produce for a given temperature and wind speed, the value of its wind chill factor. The US Weather Service uses the wind chill formula

    35.74 + 0.6215t - 35.75(v ^ 0.16) + 0.4275t(v^ 0.16)

    where

    • v is the given wind speed in miles per hour;

    • t is the given Fahrenheit temperature;

    • ^ indicates exponentiation. Remember Java does not have an exponentiation operator; but it does have Math.pow().

  • Produce when given both an integer representing a count copies and a string of interest, the repeated display of that string once per line with the number of lines equal to the count

 February 23, 2009: The selection of the day

 

Please download

 February 21, 2009: Keep it fresh

 

One more time

 February 20, 2009: Now back to the show

 

Repeat that

 February 18, 2009: I think you can! I think you can! ...

 

Downloads

 February 16, 2009: How far have we come

 

Documents

I have updated the document section to have the permissible links to class material that you can use during the test.

Preparation X

The image to the left tells much of what we have done. But it is does not speak of the underlying reason.

What we are trying to accomplish is improve our problem-solving skills, where computing is the implementation platform. To do so, knowledge of computational concepts are paramount.

I believe it is safe to say that we have all used numeric calculators, but most of us have never used their MS and MR keys that allow the saving and recalling of an intermediary calculation in the calculator memory. Although a calculator's memory is generally limited to maintaining a single value, that simple ability can still be very helpful.

The ability to remember, name, organize, and manipulate multiple values is one of the major ways programming languages transform our PCs from expensive calculators to general purpose computing systems. Without naming, sophisticated computations would be all but impossible -- try to give the relatively simple formula of the area of a circle with out using any names.

Some languages -- especially the ones of which I am a fan -- are what is called, strongly typed. A strongly-typed language requires that during its existence a named value hold only one type of value (e.g., integer, decimal, logical, string, color, ...). Programs written in a strongly-typed languages are generally less likely to use misuse values.

Java is a strongly-typed language. As such, we must define our variables and indicate with what type of value are they associated.

While naming is important for our own cognizance, the allowing of named values to be updated over time is critical. Assignment updates allow us to keep track of and understand the nature of the changes.

Ambiguity is universally recognized as an important contributor to the making of mistakes. The designers of programming languages try to ensure that nothing is left to misinterpretation. One way they help is precisely describing how calculations are carried out. The rules of operator precedence guarantee each expression has only one legal evaluation. For example in Java, the expression a + b * c always evaluates to a + (b * c) rather than to (a + b) * c.

Another way that PCs differ from calculators is their abilities to take actions only if a condition does or does not hold; and to repeat actions while the appropriate conditions hold.

Without these abilities to selectively execute and iterate, the instructions for describing how to carrying out some tasks would be intolerable. For example, we would need a different set of instructions for each size of list to be handled.

So, the ability to precisely give instructions that name, record, manipulate, evaluate, decide, and iterate, are a big part of what make programming languages so important. Without them we cannot produce the software so integral to our society.

Some of what we have come to appreciate in Java is it rich set of libraries. The libraries we have seen so far allow us to easily represent lists, graphical elements, text, files, and web sites to name just a few of many types of objects Java supports.

As we shall soon see, Java also provides the ability for us to define and manipulate new types of objects. In a programming language taxonomy, Java is called an object-oriented language. This upcoming exploration should go smoothly, as you are already able to work with objects of so many different types.

So what does the preceding rambling tell you -- some of the most important things we have considered are:

  • Variables,
  • Types,
  • Expressions,
  • Input and output - standard input and output, files, and web pages,
  • Assignment,
  • Collections - dictionaries, sets, and ordered lists,
  • Iteration,
  • Decisions.

The soon to be here testing should serve as an impetus to make sure you are paying sufficient attention to these concepts. More practically, it provides a measure of your ability to make use of these computational concepts.

To accomplish its two missions, a first test will have you

  • Evaluate expressions with arithmetic and casting operators, and indicate their values and associated types; and make use of the Math library. Success here indicates that when problem solving your computations are likely to be correctly formulated.
  • Define, initialize, manipulate, and update variables.
  • Demonstrate the ability to acquire input and produce output. If a program is not interactive what purpose does it truly serve. We have used standard input, files, and URLs as input sources. All are important. And while we have used pop-ups and graphical windows in addition to standard output, the written part of the test will only be concerned with standard output.
  • Demonstrate the ability to create and manipulate objects. The most important object types we have considered include String, Scanner, File, URL, Random, and HashMap.
    • String: some of its important capabilities allow it to indicate its size, supply substrings, and indicate whether it contain strings of interest.
    • Scanner: some of its important capabilities allow it to itself with different kinds of important sources; provide inputs; and indicate whether there are more inputs.
    • File: its most important feature has its their ability to associate itself with a particular file on our computer system. Once we have a file, we can get a Scanner to process that file.
    • URL: like a File object, it most important feature has been its ability to associate itself with pages out on the web. Using a URL's ability to set up a data stream with a web page, we can get a Scanner to process that page.
    • Random: allow us to produce number sequences that appear for all practical purposes to be random.
    • Hashmap: can ably represent an association. Its ability to take keys and and produce associated values has much applicability.
  • Demonstrate the ability to use code that iterates and make decisions.
    • While loops that iterate for a fixed number of times and those that repeat while there is more input to process
    • If statements that take the appropriate action depending upon some condition
    • For statements that iterate for a fixed number of times.
    • Local variables whose scope is limited to a particular block.
      • Remember the maxim, what happens in braces stays in braces.
  • Demonstrate that you can use the learned computational thinking concepts to solve simple problems.
  • You may find the following sheets helpful.
  •  February 14, 2009: Testing, 1, 2, 3, testing

     

    The past is often said to be the best definition of future. Others say, your mileage may differ.

    The past.

     February 13, 2009: Delegate it

     

    What's your methodology for cs101xology

    We want life to be interesting. The focus now is increasing your ability to problem solve so that you work and solve important problems. We will concentrate on both designing and implementing solutions.

    For design, we will work on breaking down problems into their component tasks. We can then implement those tasks in Java through methods.

    I expect today's class to go extremely well as you have all done the reading. In the reading, you should have learned about four kinds of methods.

    public class FourMethods {
       // does not return a value and does not takes parameters 
       public static void method1() {
           System.out.println( "simple example" );
       }
    
       // returns a value but doesn't take parameters 
       public static int method2() {
           int result = 5 * 4 * 3 * 2 * 1;
           return result;
       }
    
       // doesn't return a value but does take parameters 
       public static void method3( int a, int b ) {
           int sum = a + b;
           System.out.println( "sum: " + sum );
       }
    
       // returns a value and takes parameters 
       public static double method4( int c, double d ) {
           double result = c * d * 0.5;
           return result;
       }
    }
    

    A method is a named section of code. Sometimes a Java designer wants to limit what other Java code can use the designer's methods.

    For now, we want to make our methods available to all. We do so, by starting each method definition with the keyword public.

    Java has two fundamentally different kinds of methods. Methods that are just actions and methods that send a message to an object.

    We are going to start by writing methods that are just actions. Such methods need to use the keyword static as part of their definition.

    We can define a method that never returns a value to its user -- such methods are called void methods, because they use the keyword void in the definition.

    We can also define a method that always returns a value to its user. The type of the return value must be part of the method definition. Programmers call it the method's return type.

    A method definition must always specify what kind of information is to be passed (given) to it.

    Information is given to a method using parameters. In a definition, the designer must give for each parameter, the type and the name by which the parameter is to be called within the method.

    People refer to the parameters specified in the definition as the formal parameters.

    In the example method definitions, the formal parameters to method2() are int variables named a and b; and the formal parameters to method4() are an int variable named c and a double variable named d.

    The act of using a method to accomplish a task is known as invocation.

    The following example shows a single invocation of each of the methods. Observe that the invocations specify the library from which they come. Such specification is necessary when using methods from other libraries.

    FourMethods.method1();
    FourMethods.method3( 5, 10 );
    int i1 = FourMethods.method2();
    double d1 = FourMethods.method4( 4, 9.5 );
    

    The values given to a method as part of its invocation are called the actual parameters.

    In the following code segment, the first invocation of method2() has 5 and 7 as the actual parameters; the second invocation has 3 and 9 as the actual parameters. The first invocation of method4() has 1 and 2.25 as the actual parameters; the second invocation has 6 and 2.5 as the actual parameters.

    FourMethods.method2( 5, 7 );
    FourMethods.method2( 3, 9 );
    double d3 = FourMethods.method4( 1, 2.25 );
    double d4 = FourMethods.method4( 6, 2.5  );
    

    We consider our exploration with

     February 11, 2009: The next big thing

     

    Idiosyncratic idioms

    The if else statement can solve all your decision needs. Sometimes the normal indentation of nested if else statements does a bad job of telling people what is really go on. The idiom if else if might be the way to go -- I certainly find it useful. Very occasionally the Java switch statement might be useful. I will demonstrate both today. The if else if will come again, but not the switch.

    Many times problem solving involves massaging data to put it in a different form. For many contexts, the data needs to be processed line by line where the processing of the line requires actions word by word. For example, read text in one language and translate it to another.

    I want to stress that one most important things you can do this semester is to give multiple thorough attempts with the readings on methods on methods.

    We will sneak peek at methods using

    Next class we will tackle



    I expect it go well as you will all have done the reading.

     February 10, 2009: The next big thing

     

    Method acting

    We are going to finish out decision making on Wednesday and start considering method definitions. In the text book you should have already read all of the material on the if statement, if else statement, and the if else if idiom.

    The text talks about the switch statement. Be aware of it. I will show at most one example.

    The most important thing you can is to check out the reading on methods. We have been trying for small steps, but this one is going to be the biggest. You are ready for it. Doing the reading is imperative for you to get what you need out of class time. Give a good glance for Wednesday, a deep read for Friday.

    We will be looking on Wednesday at

    We will sneak peek at methods using

    Next class we will tackle

     February 9, 2009: The cat is away

     

    Decisions

    Please checkout the readings on HashSet and ArrayList.

    Please consider filling out the following anonymous surveys:

    • Beginning of course survey: remember to answer as you felt before the course started.
    • Interests survey: this survey will help me determine future examples.

    Please download the following files

     February 6, 2009: The road less traveled

     

    Decisions

    Please download the following files

     February 4, 2009: Up, up and away

     

    Texting

    Most problem solving requires text processing to get the information describing the particulars. The following programs could be templates for processing text.

    For the greater good

    Although the while statement can handle all our looping needs. Java also supplies the for statement to do looping. For some tasks you should find it much more convenient to use. The for loop basics can be found with the following programs.

    Its time to use our powers to do something cool

    We are going to divide into groups of 2 or 3. Our task is to develop a program that reports the weather for one of the zip codes that you provided me before class.

    I used the zip codes to create a web page that you will find help for our task. The web page consists of many pairs of lines. The first line in each pair is a zip code; the second line is the National Weather Service's forecast page for that zip code.

    I have divided the program into six parts. Our task is very doable because the National Weather Service displays forecasts in a very consistent matter.

    In broad terms, the program parts develop a HashMap that maps zip codes to weather sites; determine the zip code of interest; use the zip code to get the right National Weather Service page; process the web page to find the current forecast on the indicated National Weather service page; and display the forecast.

    We will discuss our solutions after 25 minutes or so. After class I will make my solution available.

     February 2, 2009: Say that again

     

    Dictionaries

    Sometimes a problem requires that have access to an object with dictionary-like capabilities. We might need a bunch of entries with each entry having two components. The first component is called the key. The second component is the value we associate with that key. For example, we could have entries whose keys are the names of grocery store items, the value for an item might be its cost.

    To create a dictionary in Java use HashMap. To see a HashMap in action examine

    Iteration

    Our problem solving abilities have been limited because each action we wanted to take required that we supply a statement for that action.

    Often a problem requires that some action be performed multiple times. Like many programming languages, Java supplies several ways to express that an action is to be repeated. In formal terms, Java supplies iteration constructs; informally, Java lets set up loops.

    The basic Java looping construct is the while statement. A while state has the form:

    		 while (  condition ) {
    		      actions 
    		 }
    		 
    When during the execution of your program Java reaches a while statement, it will repeatedly execute the while loop actions as long as the condition stays true.

    The actions in the while loop are often called the body of the loop.

    We will look at several programs. We start by looking at a program that sums ten user inputs. To be more flexible, we next look a program, that asks the user how many numbers to sum and then sums that many input numbers. For maximal flexibility, we look at a program that sums numbers as long as there are more inputs to process.

    Having the user enter the numbers is not always convenient. So, we will also look at programs that sum numbers from a file or that can be found on a web page.

    The while loop programs are

     January 30, 2009 Objectifying

     

    I have been asked how can you prepare for class. Well for this class spend time rereading Chapter 3, looking at the official description of the File library.

    I also strongly suggest that you print the following examples, look at them, may be make notes on them, and bring the copies to class.

    We first used variables to remember simple values for us like integers, decimals, and logical values. We moved on to using a variable to keep of a Scanner object that we could use to get input. And then there was an explosion of uses -- to name just a few we used variables to keep track of web pages, windows, colors, graphics, and strings.

    This meeting will have us manipulate File objects for representing the files on our compute. Class File comes from the java.io library.

    We will also use class Random a resource from the java.util library for creating and manipulating number generators. The generators are able to produce number sequences that pass important statistical tests indicating randomness. The number generators play important roles in simulating scenarios from the real world and from virtual worlds.

    If time permits, we will also play with

    The program generates cool pictures.

     January 28, 2009 Objectifying

     

    The previous class started us getting serious about using objects:

    • URL from the java.net library to create objects that could represent www resources.
    • Color from the java.awt library to create objects for representing colors.
    • ImageIcon from the javax.swing library to create objects to represent pictures. An ImageIcon can be constructed from a string giving name of a file or from a URL.
    • JOptionPane from the javax.swing library to create simple dialog windows for displaying images and text.
    • JFrame from the javax.swing library to create window-like objects. A JFrame window object can handle a variety of messages, including ones to configure its size, visibility, and closing behavior.
    • Graphics from the java.awt library to create objects for painting boxes in a window.

    We saw in our object usage that when we need a new object, the first thing to do is to tell Java how to construct it. Afterwards, we can manipulate the object by sending it messages. A Java library designer must specify which messages its objects will process.

    Some messages to objects include information to assist the object in taking the right action. The information comes as parameters. Parameters are passed to a message through a parenthesized list following the message name. If there is more than one parameter, then they are separated by commas.

    Java requires a library designer to specify the order that parameters are to be given in a parameter list. So be careful when sending a message to object that you know how it wants information to be passed.

    For example, the fillRect() message of a Graphics object takes four int parameters. The first two parameters specify the (x, y) location for where the box is to occur. The next two parameters specify the width and height of the box.

    Next time we will further explore the Graphics library to draw and paint different kinds of shapes. We will also get a peek look of a topic from textbook Chapter 6 -- iteration.

    Iteration is a fancy word for the repeated execution of a list of statements within a program. The more often-used word is looping -- going around and around.

    We will also look at some of the capabilities that Java provides for manipulating strings.

    To prepare for class, spend time rereading Chapter 3 and considering the following examples:

     January 26, 2009 新年快乐

     

    Getting classy

    You will often find when problem solving and doing design that the approach you taking in developing solutions requires you to be able to represent as objects, the attributes and behaviors of the components under manipulation. This approach goes under the title, object-oriented design.

    I strongly believe before you can effectively develop your own problem-specific representations that you need background experiences on the mechanics of object manipulation. The way I recommend is that you create and manipulate objects derived from some of the standard resources that are already available. Out of your experiences can come an understanding and appreciation for the object-oriented approach.

    Today we concentrate primarily on resources that support the use of objects for accessing web-based images and text, and objects of graphical nature. We will use them to create windows where we can display images and draw shapes.

    Properly speaking because the generators use an algorithm to produce their sequences, the numbers are properly called pseudo-random numbers. Most people are sloppy about the use of pseudo.

    Today we will spend time considering the following examples:

     January 23, 2009 When you least expect it

     

    Please download

     


     January 21, 2009 Change is good

     

    Please download


     January 16, 2009 Tally ho

     

    Please download

     


     January 14, 2009 Is there a doctor in the house

     

    Make sure you still have

     


     January 13, 2009: The future is now

     

    When requested, please download


     January 12, 2009: Tomorrow is the big day

     

    Download

    • If you have a Windows or Linux PC, download and install the appropriate Java JDK.

    • If you have a MAC OS X, the JDK is already installed.

    Readings

    • Textbook sections 1.1 - 1.4. 1.7, 2.1, 2.2 - 2.4
    • Wang article -- free on grounds or when using UVA VPN

    Watch


     January 8, 2009: Welcome

     

    This semester we are going to work on becoming chrestomaticians!

    The class textbook is

    • Java 5.0 Program Design
    • Authors: Jim Cohoon and Jack Davidson
    • Publisher: McGraw-Hill
    • Copyright: 2005
    • ISBN: 0073250309