Difference between revisions of "CSC212 Lab 4 2014"

From dftwiki3
Jump to: navigation, search
(Private Member Variables)
(Emulating a Python List)
 
(32 intermediate revisions by the same user not shown)
Line 7: Line 7:
  
 
<bluebox>
 
<bluebox>
Lab 4 deals with private member variables, and javadoc.
+
Lab 4 deals with private member variables, javadoc, and command line parameters.  There are 2 Moodle submissions. 
 +
<br />
 +
'''Note:''' In an effort to make you get done with the lab material early and give you time to concentrate on the homework assignment, the submission of lab programs will now be Friday evening following a lab, at 11:55 p.m.
 
</bluebox>
 
</bluebox>
 
<br />
 
<br />
 +
----
 +
----
 
=Private Member Variables=
 
=Private Member Variables=
 
<br />
 
<br />
Line 15: Line 19:
 
* Create a new program called '''Animal1.java''' containing the code below:
 
* Create a new program called '''Animal1.java''' containing the code below:
 
<br />
 
<br />
<source lang="java">
+
::<source lang="java">
 
public class Animal1 {
 
public class Animal1 {
 
         boolean isVaccinated;
 
         boolean isVaccinated;
Line 43: Line 47:
 
* In the same directory, create a second file called '''TestAnimal1.java''', which contains this code:
 
* In the same directory, create a second file called '''TestAnimal1.java''', which contains this code:
 
<br />
 
<br />
<source lang="java">
+
::<source lang="java">
 
class TestAnimal1 {
 
class TestAnimal1 {
  
Line 51: Line 55:
 
   public static void main(String[] args) {
 
   public static void main(String[] args) {
 
           // create a new animal
 
           // create a new animal
           Animal a = new Animal1( "Max", 3, false, true );
+
           Animal1 a = new Animal1( "Max", 3, false, true );
 
           a.displayBasicInfo();
 
           a.displayBasicInfo();
  
 
           // modify it.  Then display it.
 
           // modify it.  Then display it.
          a.displayBasicInfo();
 
 
           a.isVaccinated = true;
 
           a.isVaccinated = true;
 +
          a.isTattooed = false;
 
           a.age = 5;
 
           a.age = 5;
 
           a.displayBasicInfo();
 
           a.displayBasicInfo();
  
 
           // modify it some more, then display it.
 
           // modify it some more, then display it.
           a.isTattooed = true;
+
           a.isTattooed = ! a.isTattooed;
 
           a.age = a.age + 1;
 
           a.age = a.age + 1;
 
           a.displayBasicInfo();
 
           a.displayBasicInfo();
 
   }
 
   }
 +
}
 +
 +
</source>
 +
<br />
 +
* Compile and run both:
 +
 +
  javac Animal1.java TestAnimal1.java
 +
  java TestAnimal1
 +
 +
* Verify that you get the following output:
 +
 +
Max (3), tattooed, not vaccinated
 +
Max (5), not tattooed, vaccinated
 +
Max (6), tattooed, vaccinated
 +
 +
<br />
 +
==Modification==
 +
<br />
 +
* Modify the '''Animal1.java''' program and make all its member variables private.
 +
<br />
 +
::<source lang="java">
 +
        private boolean isVaccinated;
 +
        private boolean isTattooed;
 +
        private String name;
 +
        private int age;
 +
</source>
 +
<br />
 +
* Recompile both java programs.  Notice that, now, '''TestAnimal1.java''' generates many errors.  Why?
 +
* If you answer that it is because TestAnimal1 cannot access the member variables of a any longer, you are right! 
 +
* Modify both Animal1 and TestAnimal1 so that
 +
:* '''Animal1''' will now have ''mutator'' and ''inspector'' methods to access its member functions, and
 +
:* '''TestAnimal1''' will access the member variables of ''a'' by using the new accessors and mutators
 +
 +
* Here is an example of a modification you can make on Animal1.java
 +
<br />
 +
::<source lang="java">
 +
        // mutator
 +
        public void setAge( int n ) {
 +
              age = n;
 +
        }
 +
 +
        // ispector
 +
        public int getAge( ) {
 +
              return age;
 +
        }
 +
</source>
 +
<br />
 +
* And here is an example of a modification you can make on TestAnimal1.java:
 +
<br />
 +
::<source lang="java">
 +
        a.setAge( 5 );
 +
</source>
 +
<br />
 +
 +
* When you have been able to get rid of all the compiler errors for TestAnimal1.java, run the program '''TestAnimal1''' and verify that you get the same output as before:
 +
 +
Max (3), tattooed, not vaccinated
 +
Max (5), not tattooed, vaccinated
 +
Max (6), tattooed, vaccinated
 +
 +
 +
<br />
 +
----
 +
----
 +
=Javadoc=
 +
<br />
 +
==Adding the Javadoc Comments==
 +
<br />
 +
* You need to be connected to your 212a-xx account on one of the Linux machines for this all section to work.
 +
* Locate your old '''Animal.java''' class from a previous lab, or copy/paste it from [[CSC212_Examples_for_Lecture_3 | here]].
 +
* Don't worry if the member variables are not private.  In this section we're interested in generating the '''javadoc''' for this program.
 +
* Add documentation to your program using the same format as shown below.  While it might be tempting to copy/paste it, please type it.  It's the best way to remember how the javadoc syntax works:
 +
<br />
 +
::<source lang="java">
 +
/**
 +
* implements a base class for an animal.
 +
* @author thiebaut
 +
*
 +
*/
 +
public class Animal {
 +
 +
        private boolean isVaccinated; // boolean holding the property for vaccination
 +
        private boolean isTattooed; // boolean holding the property for tattoo
 +
        private String name; // contains the animal's name
 +
        private int age; // equal to the animal's age
 +
       
 +
        /**
 +
        * constructor
 +
        * @param n the name of the animal
 +
        * @param a the age of the animal
 +
        * @param v true if animal is vaccinated, false otherwise
 +
        * @param t true if animal is tattooed, false otherwise
 +
        */
 +
        Animal( String n, int a, boolean v, boolean t ) {
 +
                name            = n;
 +
                age              = a;
 +
                isVaccinated = v;
 +
                isTattooed  = t;
 +
        }
 +
       
 +
        /**
 +
        * displays all the information about the animal.
 +
        * <P>
 +
        * Format:<br />
 +
        * Rex (3), tattoed, not vaccinated
 +
        */
 +
        public void displayBasicInfo( ) {
 +
                String v = "vaccinated";
 +
                if ( !isVaccinated ) v = "not " + v;
 +
                String t = "tattooed";
 +
                if ( !isTattooed ) t = "not " + t;
 +
                System.out.print( String.format( "%s (%d), %s, %s",
 +
                                name, age, t, v ) );
 +
        }
 +
       
 +
        /**
 +
        * Main entry point.
 +
        * @param args the command line arguments.
 +
        */
 +
        public static void main(String[] args) {
 +
                Animal a = new Animal( "Max", 3, false, true );
 +
                a.displayBasicInfo();
 +
                System.out.println();
 +
        }
 +
 +
}
 +
</source>
 +
<br />
 +
 +
==Create the Javadoc==
 +
<br />
 +
 +
* At the Linux prompt, enter the following commands:
 +
<br />
 +
<center>
 +
{| class="wikitable" width="100%"
 +
! width="50%" | command
 +
! width="50%" | description
 +
|-
 +
|
 +
<tt>javadoc -d ~/public_html/myjavadoc  Animal.java</tt>
 +
|
 +
creates the javadoc for '''Animal.java''', and stores the resulting html files in the public_html folder of your home directory, in a subdirectory called '''myjavadoc'''.  The '''-d''' switch specifies that we want the output files generated to go into a specific '''d'''irectory.
 +
|-
 +
|
 +
<tt>chmod -R a+rx ~/public_html/myjavadoc</tt>
 +
|
 +
changes the access permissions to all the files belonging to the subirectory you just created, named '''myjavadoc''', in the directory '''public_html''' in your account.  '''-R''' means: visit '''recursively''' all the files and subdirectories found inside myjavadoc.  '''a+rx''' means: allow '''all''' to '''r'''ead and e'''x'''ecute the files found.  This way the Web Server on beowulf2 will be able to make your files available when requested by a Web browser.
 +
|}
 +
</center>
 +
<br />
 +
==View the Javadoc==
 +
<br />
 +
* Open a Web Browser, either on the Linux machine you are connected to, or on your laptop.
 +
* In the URL bar, enter this URL, replacing the '''xx''' letters by your own 2-letter Id:
 +
<br />
 +
<center><tt>http://cs.smith.edu/~212a-xx/myjavadoc</tt></center>
 +
<br />
 +
* Verify that you get html pages describing your program.  Explore the various pages and views of your program documentation.
 +
<br />
 +
<center>[[Image:212Javadoc1.jpg|600px]]</center>
 +
<br />
 +
<br />
 +
::Congratulations, you now know how to generate a sophisticated documentation package for your java programs!
 +
<br />
 +
==Exercise==
 +
<br />
 +
* Generate the javadoc for the Dog class, also available  [[CSC212_Examples_for_Lecture_3 | here]]. 
 +
* When generating the javadoc, use the following command:
 +
 +
<tt>javadoc -d ~/public_html/myjavadoc  Animal.java Dog.java</tt>
 +
 +
* Verify that you get both the dog and the animal classes listed on the front page of the html javadoc
 +
<br />
 +
==Moodle Question==
 +
<br />
 +
* Answer the Moodle question for '''Lab 4, Question 1'''. You have until Friday 11:55 p.m. to answer it.
 +
<br />
 +
----
 +
----
 +
<br />
 +
 +
=Accessing Command Line Arguments=
 +
<br />
 +
* Create this new Java program:
 +
<br />
 +
::<source lang="java">
 +
class PrintArgs {
 +
 +
    public static void main( String[] args ) {
 +
 +
        for ( int i=0; i<args.length; i++ )
 +
            System.out.println(
 +
                String.format( "args[%d] = %s", i, args[i] ) );
 +
 +
    }
 
}
 
}
 
</source>
 
</source>
 
<br />
 
<br />
 +
* Run it and pass it several words on the command line, as illustrated below (try different combinations of words and numbers):
 +
<br />
 +
  javac PrintArgs.java
 +
  java PrintArgs  1 2 3 4 5
 +
 +
  java PrintArgs Thursday afternoon lab on a warm September day
 +
 +
  java PrintArgs  "Smith College" is where "Sophia Smith" still lives
 +
 +
  java PrintArgs "Thursday afternoon lab on a warm September day"
 +
 +
  java PrintArgs "Thursday afternoon" lab on a warm September day
 +
 +
  java PrintArgs Thursday afternoon lab on a \"warm September\" day
 +
 +
<br />
 +
==Modification==
 +
<br />
 +
* Modify the program so that if the first argument is "-up", the program will print all the arguments that follow in uppercase, otherwise it will display the arguments as it received them. 
 +
* To get the uppercase version of a string, use the '''toUpperCase()''' method of a String variable:
 +
<br />
 +
::<source lang="java">
 +
  String name = "Smith College";
 +
 +
  System.out.println(  name.toUpperCase() ); // will print SMITH COLLEGE
 +
 +
</source>
 +
<br />
 +
 +
<br />
 +
:Example
 +
[23:09:21] ~/public_html/classes/212$: '''java PrintArgs the quick red fox jumped over the dog'''
 +
the
 +
quick
 +
red
 +
fox
 +
jumped
 +
over
 +
the
 +
dog
 +
 +
[23:10:04] ~/public_html/classes/212$: '''java PrintArgs -up the "quick red fox" jumped over the dog'''
 +
THE
 +
QUICK RED FOX
 +
JUMPED
 +
OVER
 +
THE
 +
DOG
 +
 
 +
 +
[23:11:38] ~/public_html/classes/212$: '''java PrintArgs'''
 +
 +
 +
:Note the lack of output for the last command!
 +
<br />
 +
 +
==Submission to Moodle==
 +
<br />
 +
* Go to Moodle and select the "'''Lab 4, PrintArgs Virtual programming lab'''" test.
 +
* Submit your PrintArgs.java program.  You have until Friday 11:55 p.m. to submit it.
 +
<br />
 +
----
 +
----
 +
=Emulating a Python List=
 +
<br />
 +
* Recreate the "Python List" class we saw in class.  Its code is available [[CSC212_Implementing_the_Python_List_in_Java:_Version_1#Possible_Solution| here]].
 +
* Add an '''index( ''n'' )''' and  '''rindex( ''n'' )''' method to the class. 
 +
:* index( ''n'' ) will return the index, or location, of the first occurrence starting from Index 0, of ''n'' in the array, or -1 if ''n'' is not found.
 +
:* rindex( ''n'' ) will return the index, or location, of the first occurrence starting from the end of the array, of ''n'' in the array, or -1 if ''n'' is not found.<br />
 +
* Test your program thoroughly, and make sure both methods work correctly when:
 +
:* ''n'' is not in the array,
 +
:* there are multiple occurrences of ''n'' in the array,
 +
:* when the array contains only occurrences of ''n'' (for example, the array could be filled with 9 0s, and you are searching for ''index(0)'' and ''rindex(0)'',
 +
:* when ''n'' occurs only once in the array, at Index 0
 +
:* when ''n'' occurs only once in the array, in the last position of the array.
 +
<br />
 +
You are not required to submit this program to Moodle, as the homework assignment will have you fully develop and test this program.
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
[[Category:CSC212]][[Category:Java]]

Latest revision as of 06:45, 18 September 2014

--D. Thiebaut (talk) 21:12, 17 September 2014 (EDT)





Lab 4 deals with private member variables, javadoc, and command line parameters. There are 2 Moodle submissions.
Note: In an effort to make you get done with the lab material early and give you time to concentrate on the homework assignment, the submission of lab programs will now be Friday evening following a lab, at 11:55 p.m.




Private Member Variables


  • Login to beowulf2.csc.smith.edu, grendel.csc.smith.edu, or use one of the Linux Mint machines.
  • Create a new program called Animal1.java containing the code below:


public class Animal1 {
        boolean isVaccinated;
        boolean isTattooed;
        String name;
        int age;
        
        Animal1( String n, int a, boolean v, boolean t ) {
                name             = n;
                age              = a;
                isVaccinated = v;
                isTattooed   = t;
        }
        
        public void displayBasicInfo( ) {
                String v = "vaccinated";
                if ( !isVaccinated ) v = "not " + v;
                String t = "tattooed";
                if ( !isTattooed ) t = "not " + t;
                System.out.println( String.format( "%s (%d), %s, %s", 
                                name, age, t, v ) );
        }
        
}


  • In the same directory, create a second file called TestAnimal1.java, which contains this code:


class TestAnimal1 {

   TestAnimal1() { 
   }

   public static void main(String[] args) {
           // create a new animal
           Animal1 a = new Animal1( "Max", 3, false, true );
           a.displayBasicInfo();

           // modify it.  Then display it.
           a.isVaccinated = true;
           a.isTattooed = false;
           a.age = 5;
           a.displayBasicInfo();

           // modify it some more, then display it.
           a.isTattooed = ! a.isTattooed;
           a.age = a.age + 1;
           a.displayBasicInfo();
   }
}


  • Compile and run both:
 javac Animal1.java TestAnimal1.java
 java TestAnimal1

  • Verify that you get the following output:
Max (3), tattooed, not vaccinated
Max (5), not tattooed, vaccinated
Max (6), tattooed, vaccinated


Modification


  • Modify the Animal1.java program and make all its member variables private.


        private boolean isVaccinated;
        private boolean isTattooed;
        private String name;
        private int age;


  • Recompile both java programs. Notice that, now, TestAnimal1.java generates many errors. Why?
  • If you answer that it is because TestAnimal1 cannot access the member variables of a any longer, you are right!
  • Modify both Animal1 and TestAnimal1 so that
  • Animal1 will now have mutator and inspector methods to access its member functions, and
  • TestAnimal1 will access the member variables of a by using the new accessors and mutators
  • Here is an example of a modification you can make on Animal1.java


         // mutator
         public void setAge( int n ) {
               age = n;
         }

         // ispector
         public int getAge( ) {
               return age;
         }


  • And here is an example of a modification you can make on TestAnimal1.java:


        a.setAge( 5 );


  • When you have been able to get rid of all the compiler errors for TestAnimal1.java, run the program TestAnimal1 and verify that you get the same output as before:
Max (3), tattooed, not vaccinated
Max (5), not tattooed, vaccinated
Max (6), tattooed, vaccinated





Javadoc


Adding the Javadoc Comments


  • You need to be connected to your 212a-xx account on one of the Linux machines for this all section to work.
  • Locate your old Animal.java class from a previous lab, or copy/paste it from here.
  • Don't worry if the member variables are not private. In this section we're interested in generating the javadoc for this program.
  • Add documentation to your program using the same format as shown below. While it might be tempting to copy/paste it, please type it. It's the best way to remember how the javadoc syntax works:


/**
 * implements a base class for an animal.
 * @author thiebaut
 *
 */
public class Animal {

        private boolean isVaccinated;	// boolean holding the property for vaccination
        private boolean isTattooed;		// boolean holding the property for tattoo
        private String name;			// contains the animal's name
        private int age;				// equal to the animal's age
        
        /**
         * constructor
         * @param n the name of the animal
         * @param a the age of the animal
         * @param v true if animal is vaccinated, false otherwise
         * @param t true if animal is tattooed, false otherwise
         */
        Animal( String n, int a, boolean v, boolean t ) {
                name             = n;
                age              = a;
                isVaccinated = v;
                isTattooed   = t;
        }
        
        /**
         * displays all the information about the animal.
         * <P>
         * Format:<br />
         * Rex (3), tattoed, not vaccinated
         */
        public void displayBasicInfo( ) {
                String v = "vaccinated";
                if ( !isVaccinated ) v = "not " + v;
                String t = "tattooed";
                if ( !isTattooed ) t = "not " + t;
                System.out.print( String.format( "%s (%d), %s, %s", 
                                name, age, t, v ) );
        }
        
        /**
         * Main entry point.
         * @param args the command line arguments.
         */
        public static void main(String[] args) {
                Animal a = new Animal( "Max", 3, false, true );
                a.displayBasicInfo();
                System.out.println();
        }

}


Create the Javadoc


  • At the Linux prompt, enter the following commands:


command description

javadoc -d ~/public_html/myjavadoc Animal.java

creates the javadoc for Animal.java, and stores the resulting html files in the public_html folder of your home directory, in a subdirectory called myjavadoc. The -d switch specifies that we want the output files generated to go into a specific directory.

chmod -R a+rx ~/public_html/myjavadoc

changes the access permissions to all the files belonging to the subirectory you just created, named myjavadoc, in the directory public_html in your account. -R means: visit recursively all the files and subdirectories found inside myjavadoc. a+rx means: allow all to read and execute the files found. This way the Web Server on beowulf2 will be able to make your files available when requested by a Web browser.


View the Javadoc


  • Open a Web Browser, either on the Linux machine you are connected to, or on your laptop.
  • In the URL bar, enter this URL, replacing the xx letters by your own 2-letter Id:


http://cs.smith.edu/~212a-xx/myjavadoc


  • Verify that you get html pages describing your program. Explore the various pages and views of your program documentation.


212Javadoc1.jpg



Congratulations, you now know how to generate a sophisticated documentation package for your java programs!


Exercise


  • Generate the javadoc for the Dog class, also available here.
  • When generating the javadoc, use the following command:
javadoc -d ~/public_html/myjavadoc  Animal.java Dog.java
  • Verify that you get both the dog and the animal classes listed on the front page of the html javadoc


Moodle Question


  • Answer the Moodle question for Lab 4, Question 1. You have until Friday 11:55 p.m. to answer it.





Accessing Command Line Arguments


  • Create this new Java program:


class PrintArgs {

    public static void main( String[] args ) {

        for ( int i=0; i<args.length; i++ )
            System.out.println( 
                String.format( "args[%d] = %s", i, args[i] ) );

    }
}


  • Run it and pass it several words on the command line, as illustrated below (try different combinations of words and numbers):


 javac PrintArgs.java
 java PrintArgs  1 2 3 4 5

 java PrintArgs Thursday afternoon lab on a warm September day

 java PrintArgs  "Smith College" is where "Sophia Smith" still lives

 java PrintArgs "Thursday afternoon lab on a warm September day"

 java PrintArgs "Thursday afternoon" lab on a warm September day

 java PrintArgs Thursday afternoon lab on a \"warm September\" day


Modification


  • Modify the program so that if the first argument is "-up", the program will print all the arguments that follow in uppercase, otherwise it will display the arguments as it received them.
  • To get the uppercase version of a string, use the toUpperCase() method of a String variable:


   String name = "Smith College";

   System.out.println(  name.toUpperCase() ); // will print SMITH COLLEGE



Example
[23:09:21] ~/public_html/classes/212$: java PrintArgs the quick red fox jumped over the dog
the 
quick
red
fox
jumped 
over
the
dog

[23:10:04] ~/public_html/classes/212$: java PrintArgs -up the "quick red fox" jumped over the dog
THE
QUICK RED FOX
JUMPED
OVER
THE
DOG
 

[23:11:38] ~/public_html/classes/212$: java PrintArgs


Note the lack of output for the last command!


Submission to Moodle


  • Go to Moodle and select the "Lab 4, PrintArgs Virtual programming lab" test.
  • Submit your PrintArgs.java program. You have until Friday 11:55 p.m. to submit it.




Emulating a Python List


  • Recreate the "Python List" class we saw in class. Its code is available here.
  • Add an index( n ) and rindex( n ) method to the class.
  • index( n ) will return the index, or location, of the first occurrence starting from Index 0, of n in the array, or -1 if n is not found.
  • rindex( n ) will return the index, or location, of the first occurrence starting from the end of the array, of n in the array, or -1 if n is not found.
  • Test your program thoroughly, and make sure both methods work correctly when:
  • n is not in the array,
  • there are multiple occurrences of n in the array,
  • when the array contains only occurrences of n (for example, the array could be filled with 9 0s, and you are searching for index(0) and rindex(0),
  • when n occurs only once in the array, at Index 0
  • when n occurs only once in the array, in the last position of the array.


You are not required to submit this program to Moodle, as the homework assignment will have you fully develop and test this program.