Wednesday, February 29, 2012

Lab 15: Comparable

For this lab you will implement two classes.

An Employee class with a int ssn property and a String name property. The class implements the Comparable interface by comparing the ssn of the two employees. You can learn more about Comparable by reading the case study in page 632 of your textbook.

You will also implement a Department class which maintains an array of Employees. It implements the methods
  • add(String name, int ssn) which adds a new employee to the department. You can assume that at most 10 employees will be in a department
  • toString() returns a string of all the people in the department but sorted by ssn.

For example, the sample code below generates some random employees and them prints them out:
public static void main(String[] args) {
  Department d = new Department();
  for (int i=0; i < Math.random() * 10;i++){
   int n = (int)(Math.random() * 100);
   String name = "John" + n;
   d.add(name, n);
  }
  System.out.println(d);
 }
Here is the output of one run. Notice how they are all sorted. Every time you run it the numbers will be random but will (should) appear sorted.
John3 3
John16 16
John49 49
John61 61
John92 92
Remember to turn in both files to the dropbox.cse.sc.edu.

Tuesday, February 28, 2012

Practice Condingbat Bonus Points

Once again I will give you a bonus test point for each of the following sections you finish on codingbat.com. The sections are: Array-1, Array-2, Array-3, String-3. These will have to be done before Wed, March 14 @noon.

Remember to add jmvidal@gmail.com as your 'teacher share', click on the 'prefs' link in the top of the page to set your 'teacher share'.

Homework Solutions

Here are some of my solutions for recent homeworks.

Monday, February 27, 2012

Lab 14: Undead

Everyone is a Person. But, as you know, this set is divided into the Living and the Undead.
  • The Civilian and the Slayer are are all Living.
  • Zombie, Vampire and Ghost all belong to the Undead
For this lab you will implement all these classes and in the given inheritance hierarchy. You will also implement the appropriate methods so that when you run this main on your program:
public static void main(String[] args) {
    Zombie z1 = new Zombie("Keith Richards");
    Vampire v1 = new Vampire("Angel");
    Ghost g1 = new Ghost("Bloody Mary");
    Civilian c1 = new Civilian("Rick Grimes");
    Civilian c2 = new Civilian("Glenn");
    Slayer s1 = new Slayer("Buffy Summers");
    Person[] people = {z1, v1, g1, c1, c2, s1};
    //Tell me, are you living or undead.
    for (Person p: people){
      p.alive();
    }
    System.out.println("-----------------------------");
    //OK now, say Hi
    for (Person p: people){
      p.sayHi();
    }
    System.out.println("------------------------------");
    Civilian c3 = new Civilian("Keith Richards");
    //a Person equals any other person with the same name
    System.out.println("Is Keith's zombie equal to Keith? " + z1.equals(c3));
    //except Ghosts, they are not equal to anything,
    //not even themselves.
    System.out.println("Aye you equal to yourself? " + g1.equals(g1));
    System.out.println("Are you equal to Rick? " + g1.equals(c1));
 }
you get the following output:
I am Undead.
I am Undead.
I am Undead.
I am Living.
I am Living.
I am Living.
-----------------------------
arrgh....braaaains.....
Hi, I am Angel, a vampire.
.........
Hello, I am Rick Grimes
Hello, I am Glenn
Buffy Summers here, just saving the world, again.
------------------------------
Is Keith's zombie equal to Keith? true
Aye you equal to yourself? false
Are you equal to Rick? false
Finally, your Person, Living and Undead classes should be abstract.

You will turn in all your .java files (remember, there is one for each class) at the dropbox.cse.sc.edu.


Homework 7: Camelot

The Thing class hierarchy.
For this thy sixth homework, which does appear after the fifth but before the seventh, you shall implement the simple game of Camelot. Camelot, you see, is a silly place where peasants pathetically move about insisting they are not dead yet while brave knights honor thy King by slashing them to bits.

You will implement the classes shown in in the figure, along with a Game class which holds the board description. The specific methods that each class will implement are explained in detail in the Javadoc documents for Camelot (which you must read and follow). Notice that the documentation tells you exactly which methods and which properties you need to implement for every class. The Animated class has a protected enum Direction {N,S,E,W}; which shows up as Animated.Direction in the javadocs.

The program will have a main in the Game class which looks like this:
public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    Game g = new Game();
    g.add(new Sword(3,3));
    User user = new User(1,4);
    g.add(user);
    g.add(new Knight(5,5));
    g.add(new Peasant(9,5));
    g.add(new Peasant(6,7));
    g.add(new Peasant(4,8));
    g.add(new Peasant(7,2));
    g.add(new Peasant(3,5));
    String command = "";
    do {
      System.out.println(g); //print out the game board
      System.out.print("Your move:");
      command = keyboard.next();
      user.move(command); //move the user
      g.moveAll(); //move everyone
      g.resolveConflicts(); //resolve any conflicts between those in the same row,col
    } while (user.isAlive());
 }
A sample run of the program looks like:
__________
____Y_____
__________
___S_P____
________P_
_____K____
_______P__
__P_______
__________
_____P____

Your move:south
Knight moves S
Peasant moves E
Peasant too weak to move.
Peasant too weak to move.
Peasant too weak to move.
Peasant too weak to move.
Peasant too weak to move.
__________
__________
____Y_____
___S_P____
________P_
__________
_____K_P__
__P_______
__________
______P___

Your move:west
Knight moves W
Peasant moves S
Peasant too weak to move.
Peasant moves E
Peasant too weak to move.
Peasant moves N
Peasant too weak to move.
Peasant too weak to move.
Peasant too weak to move.
______P___
__________
___Y______
___S_P__P_
__________
__________
____K___P_
__P_______
__________
__________

Your move:south
Knight moves W
Peasant moves N
Peasant too weak to move.
Peasant moves S
Peasant too weak to move.
Peasant too weak to move.
Peasant moves E
Peasant too weak to move.
Peasant moves E
Peasant too weak to move.
User picks up Sword
__________
__________
__________
___Y__P_P_
__________
__________
___K______
___P____P_
__________
______P___

Your move:east
Knight moves W
Peasant too weak to move.
Peasant too weak to move.
Peasant moves E
Peasant too weak to move.
Peasant moves W
Peasant too weak to move.
Peasant too weak to move.
__________
__________
__________
____Y_P__P
__________
__________
__K_______
__P_____P_
__________
______P___

Your move:east
Knight moves S
Peasant too weak to move.
Peasant moves S
Peasant too weak to move.
Peasant moves W
Peasant too weak to move.
Peasant too weak to move.
Peasant moves S
Peasant too weak to move.
Bloodthristy Knight kills a P
__________
__________
__________
_____Y__P_
______P___
__________
__________
__K_______
________P_
______P___

Your move:south
Knight moves W
Peasant moves W
Peasant too weak to move.
Peasant moves W
Peasant too weak to move.
Peasant moves N
Peasant too weak to move.
Peasant moves S
Peasant too weak to move.
__________
__________
________P_
__________
_____Y____
______P___
__________
_K________
_______P__
_____P____

Your move:quit
Knight moves W
Peasant moves E
Peasant too weak to move.
Peasant moves S
Peasant too weak to move.
Peasant moves S
Peasant too weak to move.
Peasant too weak to move.

Basically, the user tells the User how to move (N,S,E,W). The knights move randomly (one of N,S,E,W) on each turn. The peasants flip a coin, if heads they stay put otherwise they move randomly (one ofN,S,E,W). The world is 10 by 10 and wraps around.

The resolveconflicts method is described in the javadocs. It goes over every Thing. If there is another Thing in the same row,col position then, if the Thing is a Knight it kills (removes) any Thing else there. If it is the user then if it finds the sword there it picks it up (thus killing it) and it is it a peasant it kills it.

I recommend you implement this program in the following order:
  1. The Thing hierarchy, start at the top and work your way down. Start with the properties, then the toString() methods, then the move() methods.
  2. The Game class, its properties and constructor.
  3. Game.toString(), test it.
  4. Game.add()
  5. Game.remove()
  6. Game.thingsAt()
  7. Game.moveAll(): this should just call move() on every thing.
  8. Finally, Game.removeConflicts()
This homework is due on Monday, March 12 @noon. Camelot, it is a silly place.


Interfaces and Abstract Classes

The last two topic from Chapter 8, which is the last Chapter we will cover before Test 2, are Interfaces and Abstract classes. We will cover these on lecture Monday and the rest of the lectures until the test we will be doing practice exercises.








Also, I just found this set of Java tutorials which are very nicely done, and cover a lot of the same material we are covering.

Friday, February 24, 2012

Some Lab Solutions

Lingxi reminds me that it is time I post my solutions to the labs, so here they are.

I don't have a solution for lab 11. If you have a good solution to it, feel free to post a link to it in the comments.

More Array Examples

Below is an example of a more complicated program using arrays; I write a short program to print out a row from Pascal's triangle. As I mention in the video, this video was inspired by a blog post on good interview questions for developers. Some employers feel that asking candidates to write this program on a whiteboard is a good way to filter out those who can code from those who cannot. I can say that this would be a great question for the final in this class (well, not anymore).


Wednesday, February 22, 2012

Lab 13: Connect Four


For this lob you will implement a simple text-based version of the Connect Four game.

The Connect Four board has 6 rows and 7 columns. Your program will display a text-based board and then ask the user to enter the column on which to drop a piece. The program will then show the new board with the piece dropped in the appropriate place. The colors (players) will alternate. You do not have to check to see if one of them has won (but, it would be very good practice for the test!).

Below is a sample interaction with the program:
0 1 2 3 4 5 6 
_ _ _ _ _ _ _ 
_ _ _ _ _ _ _ 
_ _ _ _ _ _ _ 
_ _ _ _ _ _ _ 
_ _ _ _ _ _ _ 
_ _ _ _ _ _ _ 

Enter column for B's move:0
0 1 2 3 4 5 6 
_ _ _ _ _ _ _ 
_ _ _ _ _ _ _ 
_ _ _ _ _ _ _ 
_ _ _ _ _ _ _ 
_ _ _ _ _ _ _ 
B _ _ _ _ _ _ 

Enter column for R's move:0
0 1 2 3 4 5 6 
_ _ _ _ _ _ _ 
_ _ _ _ _ _ _ 
_ _ _ _ _ _ _ 
_ _ _ _ _ _ _ 
R _ _ _ _ _ _ 
B _ _ _ _ _ _ 

Enter column for B's move:0
0 1 2 3 4 5 6 
_ _ _ _ _ _ _ 
_ _ _ _ _ _ _ 
_ _ _ _ _ _ _ 
B _ _ _ _ _ _ 
R _ _ _ _ _ _ 
B _ _ _ _ _ _ 

Enter column for R's move:1
0 1 2 3 4 5 6 
_ _ _ _ _ _ _ 
_ _ _ _ _ _ _ 
_ _ _ _ _ _ _ 
B _ _ _ _ _ _ 
R _ _ _ _ _ _ 
B R _ _ _ _ _ 

Enter column for B's move:6
0 1 2 3 4 5 6 
_ _ _ _ _ _ _ 
_ _ _ _ _ _ _ 
_ _ _ _ _ _ _ 
B _ _ _ _ _ _ 
R _ _ _ _ _ _ 
B R _ _ _ _ B 

Enter column for R's move:6
0 1 2 3 4 5 6 
_ _ _ _ _ _ _ 
_ _ _ _ _ _ _ 
_ _ _ _ _ _ _ 
B _ _ _ _ _ _ 
R _ _ _ _ _ R 
B R _ _ _ _ B 

Enter column for B's move:


You will implement a Board class which holds the state of the board using a 2-dimensional array. This class should have a toString method and a drop method which handles the dropping of a new piece on the board.

As always, turn it in on the dropbox.cse.sc.edu.



Insertion Sort

Below is a video about the insertion sort, which is different from the selection sort I talked about in class today, but not by much. They are very similar.


Inheritance and Polymorphism

In today's lecture we started talking about inheritance and polymorphism. These are covered in Chapter 8 of the textbook and below.

Inheritance





Polymorphism


Tuesday, February 21, 2012

Volunteer VM Testers Needed

Our IT department is testing out a remote virtual machine hosting solution. In it you use your computer to connect and use the software that is running in a second computer which is actually running on a server somewhere in Swearingen and is a virtual machine. A virtual machine is what you get when you turn a computer into a software program, so one physical machine can run many virtual machines. For example, I showed you on my Mac laptop how I can run a Windows7 virtual machine, and switch back and forth between them. In that scenario my mac was the host and the windows machine was a virtual machine. I could have had more windows machines (or Linux), as long as I had enough RAM.

If you want to test their setup, and see if you can run eclipse on the virtual machine and actually do one of the labs or homeworks in it, just follow these instructions. If there are any issues or problems report them to Naik Himanshu <himanshu@cec.sc.edu>.

This will take time, so please only do it if you feel comfortable with your work in class.

Monday, February 20, 2012

Lab 12: Random Cyphers

Enigma Machine
For this lab you will write a program that first generates a random cypher key and then uses that key to encrypt the users' messages. The cypher key is just a mapping from every letter in English (just the lower case letters) to another one.

A simple way to generate a random cypher is the following
  1. Create a char[] cypher array where cypher[0] = 'a', cypher[1] = 'b' and so on. Remember that if i is an integer then (char)('a' + i) will be 'b' when i==1, 'c' when i==2, and so on.
  2. Then, to randomize cypher simply pick 2 random indexes in the array and swap the values. Repeat this 100 times and the array should be properly randomized.

You will then use this cypher array to encrypt the user's message. Below is a sample interaction with the user:

Our cypher is:
abcdefghijklmnopqrstuvwxyz
jbeqkmrvayihonpfgdsxutczlw
Enter your message:
abc xyz
The encrypted message is:
jbe zlw
Enter your message:
Launch code Alpha, Tango, Tango, Bravo, Macho
The encrypted message is:
hjunev epqk jhfvj, xjnrp, xjnrp, bdjtp, ojevp
Enter your message:
how about a nice game of chess?
The encrypted message is:
vpc jbpux j naek rjok pm evkss?
Enter your message:

Tip: Remember to toLowerCase his input and ignore spaces and other characters. You will find that either charAt or toCharArray will come in handy

Tip:If you have char c; then cypher[(int)('a' - c)] will access the 0th position of cypher when c=='a'.

As always, turn it in on the dropbox.cse.sc.edu.

Homework 6: Frequency Stability

How random can you be? How can we tell how random you are? Watch the following video to learn how we determine someone's frequency stability.



For this problem you will implement a program that asks the user to type in a random sequence of 0's and 1's and then prints a distribution of all the length-3 substrings in his input, as well as the standard deviation in these numbers. The following is a sample interaction of the user with the program:
Enter random sequence of 0 and 1s:
00000111
The distribution of length=3 substrings is:
000 3
001 1
010 0
011 1
100 0
101 0
110 0
111 1
Deviation = 0.9682458365518543
The computer's random sequence is:
01010100
The distribution of length=3 substring is:
000 0
001 0
010 3
011 0
100 1
101 2
110 0
111 0
Deviation = 1.0897247358851685
The user enters a random string of 0s and 1s (you can assume he does this correctly and does not enter other characters). The program then counts how many times each of the eight possible sequences of length 3 appears and prints these out. It then calculates the standard deviation for these counts.

Finally, the program generates a random sequence of 0s and 1s of the same length as the user's and then prints out the same calculations for this sequence. Here is another run, one where I try to be random:
Enter random sequence of 0 and 1s:
0101010101010101000101001001001001001001010101011111010100101010010010010101010101010010
The distribution of length=3 substrings is:
000 1
001 12
010 34
011 1
100 12
101 22
110 1
111 3
Deviation = 11.266654339243749
The computer's random sequence is:
1000111001110111010010110110100110110111100001011000001111010100011100111100001010110000
The distribution of length=3 substrings is:
000 11
001 9
010 8
011 13
100 10
101 12
110 13
111 10
Deviation = 1.713913650100261
As you can see, I'm not very good at being random.

You will want to use arrays in this program.

This homework is due Monday, February 27 @noon in the dropbox.cse.sc.edu.

Friday, February 17, 2012

More Fun with Arrays:2D, Sorting, Tic-Tac-Toe

Next week we will do a lot of array examples. First, we have multi-dimensional arrays:





Here is an example of how to implement the insertion sort algorithm.





Finally, an example of how to build a tic-tac-toe board using arrays.


Wrapper Classes and Arrays

Next week we will be going over wrapper classes





and getting deep into Arrays





Here is an example of using an Array within a class.





Thursday, February 16, 2012

Building an Immutable Class, Unit testing, Packages

In lecture yesterday I covered the building of an immutable class, using the final keyword. The video below recapitulates what we learned.


Immutable Distance Class





The video below talks about Java packages and how to create them in eclipse.


Packages


Wednesday, February 15, 2012

Lab 11: Temperature

Thermometer
For this lab you will do Programming Project 10 from Chapter 6 of the textbook (page 468).

Make sure you do write the driver program it asks for. This should be on your main, so that when we run your program all it does is run all the tests.

Monday, February 13, 2012

Lab 10: Grade Distribution

You will implement a class called GradeDistribution which keeps the number of As, Bs, Cs, Ds, and Fs there are in a class (just the number of letter grades, not the number grades). You will then implement methods for this class which printout the total number of grades in the class (that is, the total number of students), a nice text-y bar chart, and the median grade. For example, the following code:

public static void main(String[] args) {
 GradeDistribution grades = new GradeDistribution();
 grades.setAs(4);
 grades.setBs(10);
 grades.setCs(11);
 grades.setDs(1);
 grades.setFs(5);
 //print a pretty graph
 System.out.println(grades);
 System.out.println("There are a total of " + grades.getNumGrades() + " grades.");
 System.out.println("The median grade is " + grades.getMedian());
  
 grades.setAs(20);
 grades.setBs(15);
 grades.setCs(10);
 grades.setDs(5);
 grades.setFs(0);
 System.out.println(grades);
 System.out.println("There are a total of " + grades.getNumGrades() + " grades.");
 System.out.println("The median grade is " + grades.getMedian());

}

should print out:
**** A
********** B
*********** C
* D
***** F

There are a total of 31 grades.
The median grade is C
******************** A
*************** B
********** C
***** D
 F

There are a total of 50 grades.
The median grade is B

Tip: The median grade is the one in the middle (plus or minus one) if you lay them all out in order (from F to A, or A to F). To calculate it just find the middle position and then...find the grade that is in the middle. For example, if everyone got A's then the median grade is an A, if 20 people got A's and 10 got B's then the median is an A, etc.

As always, turn it in on the dropbox.cse.sc.edu.

Homework 5: Family Tree

In this homework you will implement a simple Person class that has the following data members:

  • String: name
  • int: yearOfBirth
  • boolean: isFemale
  • Person: mother
  • Person: father
and which implements the following methods:
  • Person(String name, boolean isFemale, int yearOfBirth): constructor
  • Person(String name, boolean isFemale, int yearOfBirth, Person mother, Person father): constructor
  • equals(Person other): returns true if this person and other have the same name and were born in the same year.
  • boolean isSiblingOf(Person other): returns true if this person and other are siblings
  • boolean isCousinOf(Person other): return true if this person and other are first cousins (at least one of their parents are siblings)
  • Person getPaternalGrandfather(): returns the paternal grandfather (dad's dad).

To test your program us the following main (cf. The Weasley Family)
public static void main(String[] args) {
        //Part of the Weasley family tree, from http://www.hp-lexicon.org/wizards/weasley.html
 Person molly = new Person("Molly Weasley", true, 1950);

 //Person.toString() prints out a nice view  of the person
 System.out.println(molly); //print out molly
  
 //Implement these constructors
 Person arthur = new Person("Arthur Weasley", false, 1950);
 Person fleur = new Person("Fleur Delacour", true, 1977);
 Person bill = new Person("Bill Weasley", false, 1970);
  
 //Implement these setters
 bill.setFather(arthur);
 bill.setMother(molly);
 System.out.println(bill); //print out bill
  
 //Implement these constructors
 Person charlie  = new Person("Charlie Weasley", false, 1972, molly, arthur);
 Person percy = new Person("Percy Ignatius Weasley", false, 1976, molly, arthur);
 Person fred = new Person("Fred Weasley", false, 1978, molly, arthur);
 Person george = new Person("George Weasley", false, 1978, molly, arthur);
 Person ron = new Person("Ronald \"Ron\" Bilius Weasley", false, 1980, molly, arthur);
 Person ginny = new Person("Ginerva \"Ginney\" Molly Weasley", true, 1981, molly, arthur);
 System.out.println(ron); //print out ron
  
 //Implement Person.isSibling(Person p) which returns true if they are siblings
 System.out.println("Are fred and george siblings? " + fred.isSiblingOf(george));
 System.out.println("Are molly and george siblings? " + molly.isSiblingOf(george));
  
 Person hermione = new Person("Hermione (Granger) Weasley", true, 1979);
 Person rose = new Person("Rose Wealey", true, 2006,hermione,ron);
 Person hugo = new Person("Hugo Wealey", true, 2008, hermione, ron);
 System.out.println("Rose's paternal grandpa is:\n" + rose.getPaternalGrandfather());
 System.out.println("Ron's paternal grandpa is:\n" + ron.getPaternalGrandfather());
 Person harry = new Person("Harry Potter", false, 1980);
 Person james = new Person("James Sirius", false, 2005, ginny, harry);
 Person albus = new Person("Albus Severus", false, 2006, ginny, harry);
 Person lily = new Person("Lily Luna", true, 2007, ginny, harry);
  
 //Implement the Person.isCousin(Person p) which returns true if they are first cousins.
 //  X and Y are first cousins if one of their parents are siblings.
 System.out.println("Are rose and albus cousins? " + rose.isCousinOf(albus));
 System.out.println("Are albus and rose cousins? " + albus.isCousinOf(rose));
 System.out.println("Are harry and ron cousins? " + harry.isCousinOf(ron));
 System.out.println("Are lily and charlie cousins? " + lily.isCousinOf(charlie));
 System.out.println("Are james and albus cousins? " + james.isCousinOf(albus));
 System.out.println("Are james and fred cousins? " + james.isCousinOf(fred));
 System.out.println("Are james and hugo cousins? " + james.isCousinOf(hugo));
 System.out.println("Are james and rose cousins? " + james.isCousinOf(rose));

 }

When you run that main it should print out:
Molly Weasley (F) 1950
    Mother=unknown
    Father=unknown
Bill Weasley (M) 1970
    Mother=Molly Weasley
    Father=Arthur Weasley
Ronald "Ron" Bilius Weasley (M) 1980
    Mother=Molly Weasley
    Father=Arthur Weasley
Are fred and george siblings? true
Are molly and george siblings? false
Rose's paternal grandpa is:
Arthur Weasley (M) 1950
    Mother=unknown
    Father=unknown
Ron's paternal grandpa is:
null
Are rose and albus cousins? true
Are albus and rose cousins? true
Are harry and ron cousins? false
Are lily and charlie cousins? false
Are james and albus cousins? false
Are james and fred cousins? false
Are james and hugo cousins? true
Are james and rose cousins? true

This homework is due Monday, February 20 @noon in the dropbox.cse.sc.edu.

Sunday, February 12, 2012

Static Properties and Methods

Chapter 6 covers static member variables and methods. The video below summarizes these concepts.


Friday, February 10, 2012

Equals and Constructors

Next week we will also cover what it means for two object to be "equal". Chapter 6 will then introduce us to constructors.


Are those two objects equal?



Constructors



Thursday, February 9, 2012

Classes, Object, and Methods

Next week we will continue delving deeper into Java classes, objects, and methods. Watch the following videos.


Methods calling Methods



Call by reference, call by value (or, what can go wrong when you pass an object as an argument to a method)



Java Strings are immutable



Lab Test Solutions

Here are my solutions for Lab test 1, Lab test 2, Lab test 3, and Lab test 4.

Wednesday, February 8, 2012

Lab 9: Medical Records

In this lab you will implement your first class: MedicalRecord. A MedicalRecord holds a few pieces of information, namely, the name of the patient, the date of birth (DOB), the last visit, and a diagnosis record.

Your MedicalRecord class will have the following data members
  1. private String name
  2. private String dateOfBirth
  3. private String lastVisit
  4. private String diagnosis

as well as setters and getters for each one these.

You will also add the following methods:
  1. toString() which returns the record formatted as seen below
  2. MedicalRecord(String name) which constructs one instance with the given patient's name
  3. appendDiagnosis(String msg) which appends msg to the current diagnosis.

For example, the following code:
 public static void main(String[] args) {
  MedicalRecord bob = new MedicalRecord("Bob Smith");
  bob.setDob("01/01/1960");
  System.out.println(bob);
  System.out.println("---");
  bob.setLastVisit("02/01/2012");
  System.out.println(bob);
  System.out.println("---");
  bob.setDiagnosis("OK");
  System.out.println(bob);
  System.out.println("---");
  bob.appendDiagnosis("1/1/12- His head hurts");
  bob.appendDiagnosis("1/2/12- His toe is green");
  System.out.println(bob);
  System.out.println("---");
  bob.appendDiagnosis("1/10/12- OK now");
  System.out.println(bob);
  System.out.println("---");

 }
when run with your class should print out:
Bob Smith
Born: 01/01/1960
Last visit: null
Diagnosis: null
---
Bob Smith
Born: 01/01/1960
Last visit: 02/01/2012
Diagnosis: null
---
Bob Smith
Born: 01/01/1960
Last visit: 02/01/2012
Diagnosis: OK
---
Bob Smith
Born: 01/01/1960
Last visit: 02/01/2012
Diagnosis: OK
1/1/12- His head hurts
1/2/12- His toe is green
---
Bob Smith
Born: 01/01/1960
Last visit: 02/01/2012
Diagnosis: OK
1/1/12- His head hurts
1/2/12- His toe is green
1/10/12- OK now
---

Test 1 Distribution

I have graded Test 1, below is the points (not grades) distribution. I will talk about grades in class.



Monday, February 6, 2012

Java Classes, Properties and Methods

On Thursday's class we will introduce Java Classes. You should have read Chapter 5 and watched the videos below by then.


Java Classes in Eclipse


Java Getters and Setters

Test 1 Solutions

Test 1s, and their solutions. I am not showing the output of the programs. Just paste them into eclipse and run them to see what it does.

This is the test for one of the sections:

  1. (25%) What does the following program print out when run?

    	public static void main(String[] args) {
    		boolean bool = true;
    		int i = 0;
    		for (i=0; i < 5; i++){
    			System.out.println(i);
    			if (bool && (i % 2 == 0) )
    				System.out.println("Ob");
    			else if (i < 3)
    				System.out.println("La");
    			else if (i % 2 == 0 || i > 3 )
    				System.out.println("Di");
    		}
    		System.out.println(i < 10);
    	}
              
  2. (25%) What does the following program print out when run?
    	public static void main(String[] args) {
    		String word = "CCBA";
    		while (word.length() > 0){
    			char c = word.charAt(0);
    			System.out.print(c); //notice: print
    			word = word.substring(1);
    			int x = 0;
    			switch (c) { //watch out for missing breaks!
    				case 'A':
    					x = 4;
    				case 'B':
    					x = 2;
    					break;
    				case 'C':
    					x = 3;
    			};
    			for (int i=0; i < x; i++){
    				System.out.print("*"); //print (NOT println)
    			}
    			System.out.println(""); //move to next line
    		}
    	}
            
  3. (25%) Write a program that asks the user to enter a
    word and then prints YES if the first 3 characters of the word
    are the same as the last 3 characters (and in the same order).
    Otherwise, or if the word has fewer than 3 characters, the
    program prints NO. Some sample runs:
    Enter word:alphabet
    NO
    ---we run the program again---
    Enter word:abalataba
    YES
    ---we run the program again---
    Enter word:javaisjav
    YES
    ---we run the program again---
    Enter word:javaisajv
    NO
    ---we run the program again---
    Enter word:jav
    YES
    ---we run the program again---
    Enter word:b
    NO
              
    Answer:
    	public static void main(String[] args) {
    		Scanner keyboard = new Scanner(System.in);
    		System.out.print("Enter word:");
    		String word = keyboard.next();
    		if (word.length() < 3)
    			System.out.println("NO");
    		else if (word.substring(0,3).equals(word.substring(word.length() - 3))) {
    			System.out.println("YES");
    		}
    		else
    			System.out.println("NO");
    	}
    
  4. (25%) Write a program that ask the user to enter a
    sentence and then prints out that same sentence but with every
    other character turned into its uppercase equivalent. For
    example:
    Enter message:this program is impossible to write
    tHiS PrOgRaM Is iMpOsSiBlE To wRiTe
    ---we run the program again---
    Enter message:fun in the sun
    fUn iN ThE SuN
              
    Answer:
    	public static void main(String[] args) {
    		Scanner keyboard = new Scanner(System.in);
    		System.out.print("Enter message:");
    		String msg = keyboard.nextLine();
    		String result = "";
    		for (int i=0; i < msg.length(); i++){
    			String letter = msg.substring(i,i+1);
    			if (i%2 == 0) {
    				result += letter;
    			}
    			else {
    				result += letter.toUpperCase();
    			}
    		}
    		System.out.println(result);
           }
    
This is the test for the other section.
  1. (25%) What does the following program print out when run?

    	public static void main(String[] args) {
    		int i = 5;
    		int sum = 0;
    		for (i=5; i > 0; i--){
    			System.out.println(i);
    			sum += (i * 2);
    			if (i > 2 && i < 4)
    				System.out.println("Ob");
    			else if (i % 3 > 0)
    				System.out.println("La");
    		}
    		System.out.println(sum);
    	}
              

  2. (25%) What does the following program print out when run?
    	public static void main(String[] args) {
    		String word = "ABCCAB";
    		while (word.length() > 0){
    			char c = word.charAt(0);
    			System.out.print(c); //notice: print
    			word = word.substring(2);
    			int x = 0;
    			switch (c) { //watch out for missing breaks!
    				case 'A':
    					x = 3;
    				case 'B':
    					x = 1;
    					break;
    				case 'C':
    					x = 4;
    			};
    			if (x <= 1)
    				System.out.println(" alan");
    			else if (x <= 3)
    				System.out.println(" turing");
    			else
    				System.out.println(" lives");
    		}
    	}
            
  3. (25%)
    Write a program that asks the user to enter a word. If the
    word has an 'a' in it then the program will print out the letter
    that comes after the first 'a' in the word (from
    left-to-right). If there are no 'a's or if the 'a' is the last
    character in the word then the program will print out
    "OOPS". Below are some sample runs.
    Enter word:eventful
    OOPS
    ---we run the program again---
    Enter word:java
    v
    ---we run the program again---
    Enter word:nova
    OOPS
    ---we run the program again---
    Enter word:animation
    n
    
    Answer:
    	public static void main(String[] args) {
    		Scanner keyboard = new Scanner(System.in);
    		System.out.print("Enter word:");
    		String word = keyboard.next();
    		int aIndex = word.indexOf('a');
    		if (aIndex == -1) {
    			System.out.println("OOPS");
    		} 
    		else if (aIndex == word.length() -1 ){
    			System.out.println("OOPS");
    		}
    		else {
    			System.out.println(word.charAt(aIndex + 1));
    		}
    	}
    
  4. (25%) Write a program that asks the user to enter a
    sentence. The program will then print out the total number of
    times the letter 'a' appears in the sentence, as well as the total number of
    times the two letters 'an' appear (in that order). Below are
    some sample runs.
    Enter message:banana
    Number of As = 3
    Number of ANs = 2
    ---we run the program again---
    Enter message:the music of the night
    Number of As = 0
    Number of ANs = 0
    ---we run the program again---
    Enter message:are you suggesting that coconuts migrate?
    Number of As = 3
    Number of ANs = 0
    
    Answer:
    	public static void main(String[] args) {
    		Scanner keyboard = new Scanner(System.in);
    		System.out.print("Enter message:");
    		String msg = keyboard.nextLine();
    		int numAs =0;
    		int numANs = 0;
    		for (int index = 0; index < msg.length(); index++){
    			if (msg.charAt(index) == 'a') {
    				numAs++;
    				//take advantage of short-circuit evaluation
    				if (index + 1 < msg.length() && msg.charAt(index + 1) == 'n') 
    					numANs++;
    			}
    		}
    		System.out.println("Number of As = " + numAs);
    		System.out.println("Number of ANs = " + numANs);
    	}
    



Homework 4: Moire


In this homework you will start with the code I gave you in Lab 7 change the program so that it generates the Moire pattern shown on the right.

What you are seeing in the screenshot are two sets of concentric circles. The centers of the circles are 100 pixels apart. The circles have a width of 5, and the diameter of a circle is 20 pixels larger than its next smallest one. Diameters range from 20 to 480 pixels.

Hint: You can change the width of the 'pen' used for drawing to 5 pixels with the line g2.setStroke(new BasicStroke(5)).

Hint: A circle is just an oval whose width and height are the same.

This homework is due Monday, February 13 @noon in the dropbox.cse.sc.edu.

Saturday, February 4, 2012

Test Grading Rubric

The grading rubric for the lab tests is as follows:

  • If it works for all inputs and has the student's name and email and is reasonable code, then 100.
  • If the program works but does it in a very silly way, like hard-coding gigantic Strings and printing them out instead of using a for loop to generate the String, then it will get at most 50.
  • If it works for almost all inputs, or is almost perfect: 90:
  • If it works for some inputs, or mostly works for all inputs: 80
  • It if works for at least 1 input, or does something reminiscent of what we asked for: 70
  • If it does not compile then it will get at most 50.
  • If the program consists only of a main and the usual Scanner lines: 10.

For the in-class test (handwritten) the rubric is similar except that I will not be taking points off for missing details like: missing imports, semicolons, closing braces, etc. Still, you should try to make your code as close to compilable as possible to ensure it is not ambiguous (thus, wrong).

The Hacker Way

In his letter to investors, Zuckerberg talks about the "Hacker way", echoing old ideas on what hacking really/used-to mean. The following excerpt from his letter also serves as great advice on how to write code, for life, for the future, for this class.
The Hacker Way is an approach to building that involves continuous improvement and iteration. Hackers believe that something can always be better, and that nothing is ever complete. They just have to go fix it — often in the face of people who say it’s impossible or are content with the status quo.

Hackers try to build the best services over the long term by quickly releasing and learning from smaller iterations rather than trying to get everything right all at once. To support this, we have built a testing framework that at any given time can try out thousands of versions of Facebook. We have the words “Done is better than perfect” painted on our walls to remind ourselves to always keep shipping.

Hacking is also an inherently hands-on and active discipline. Instead of debating for days whether a new idea is possible or what the best way to build something is, hackers would rather just prototype something and see what works. There’s a hacker mantra that you’ll hear a lot around Facebook offices: “Code wins arguments.”

Hacker culture is also extremely open and meritocratic. Hackers believe that the best idea and implementation should always win — not the person who is best at lobbying for an idea or the person who manages the most people.

Friday, February 3, 2012

Lab Solutions

Here are my solutions to some of the past labs and homeworks.

Remember, the only way to learn to program is by programming. Practice, practice, practice. I recommend:

  1. Do the exercises in the textbook.
  2. Do codingbat.com
  3. Look at my answers and the ones in the textbook: compare with yours.
  4. If confused, try watching one of my screencasts on the topic.

Girls in a Tech World



Wednesday, February 1, 2012

Lab 8: Words and Vowels

In this lab you will write a program that asks the user to type in some sentences and then tells him how many words and how many vowels (a, e, i, o, u) there are in the text he typed in. Here is a sample transcript:
I will count your vowels. Enter your sentences.
Hit enter when done
Sentence (hit ENTER when done):Once upon a midnight dreary
Sentence (hit ENTER when done):while I pondered
Sentence (hit ENTER when done):weak
Sentence (hit ENTER when done):and
Sentence (hit ENTER when done):weary
Sentence (hit ENTER when done):
There are 20 vowels.
There are 11 words.

You can assume that there is always a space between every two words, but remember that there could be a line with just one word, and no spaces, as the above example shows.

Hint: use Scanner.nextLine() to read the whole line.

Hint: use String.charAt

As always, turn it in at the dropbox.cse.sc.edu, Lab 8.