Friday, October 30, 2009

Chapter 10 Lecture

Below is the screencast for the chapter 10 which deals with reading and writing streams to files. I/O operations like these are slightly different on every programming language, but the basic ideas are the same.

CSCE 145: Chapter 10 from Jose Vidal on Vimeo.

You must have watched the screencast by Tuesday, November 3 before class. The textbook slides are below.

Homework 7: Field Notebook

For this homework you will implement a minimal field notebook, as might be used by a bird or butterfly watcher on the field (on her Android phone, one presumes). Your application will need to implement at least three classes:
  1. Reading is a specific observation that the user makes. This class has data members
    1. date of type Date, the date of the reading, which you will assign automatically to the current time.
    2. species is a String which is the name of the species of animal the user saw.
    3. count is an int that is the number of animals the user saw.
    4. comment a String comment
  2. Notebook is a collection of up to 100 readings. It should support, adding a new reading, printing, saving to a file, and reading back from a file.
  3. NegativeCountException is an Exception that you will raise if the user ever tries to enter a negative number of animals. Your program will throw this exception and also catch it, so the program does not crash.

Your program will support the saving of the whole notebook to a file and the subsequent loading of a notebook from a file. The whole thing will be controlled via a text-based interface, as such:

Command list: 

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:r
Species name:swallowtails
Count:3
Comment:Fluttering in the sunshine.
Command list: 

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:r
Species name:Jezebel
Count:11
Comment:Hard to count in the daylight.
Command list: 

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:l
Fri Oct 30 14:11:31 EDT 2009 swallowtails 3 Fluttering in the sunshine.
Fri Oct 30 14:12:02 EDT 2009 Jezebel 11 Hard to count in the daylight.

Command list: 

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:r
Species name:Duke of Burgundy
Count:1
Comment:Did not expect to see this one here!
Command list: 

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:l
Fri Oct 30 14:11:31 EDT 2009 swallowtails 3 Fluttering in the sunshine.
Fri Oct 30 14:12:02 EDT 2009 Jezebel 11 Hard to count in the daylight.
Fri Oct 30 14:12:37 EDT 2009 Duke of Burgundy 1 Did not expect to see this one here!

Command list: 

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:w
Enter name of file to write to:notebook.dat
Command list: 

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:l
Fri Oct 30 14:11:31 EDT 2009 swallowtails 3 Fluttering in the sunshine.
Fri Oct 30 14:12:02 EDT 2009 Jezebel 11 Hard to count in the daylight.
Fri Oct 30 14:12:37 EDT 2009 Duke of Burgundy 1 Did not expect to see this one here!

Command list: 

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:q
Bye bye. //at this point the program stops.

//we start it again
Command list: 

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:l

Command list: 

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:o
Enter name of file to read:notebook.dat
Command list: 

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:l
Fri Oct 30 14:11:31 EDT 2009 swallowtails 3 Fluttering in the sunshine.
Fri Oct 30 14:12:02 EDT 2009 Jezebel 11 Hard to count in the daylight.
Fri Oct 30 14:12:37 EDT 2009 Duke of Burgundy 1 Did not expect to see this one here!

Command list: 

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:r
Species name:Speckled wood
Count:200
Comment:A gaggle of butterflies.
Command list: 

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:l
Fri Oct 30 14:11:31 EDT 2009 swallowtails 3 Fluttering in the sunshine.
Fri Oct 30 14:12:02 EDT 2009 Jezebel 11 Hard to count in the daylight.
Fri Oct 30 14:12:37 EDT 2009 Duke of Burgundy 1 Did not expect to see this one here!
Fri Oct 30 14:14:53 EDT 2009 Speckled wood 200 A gaggle of butterflies.

Command list: 

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:r
Species name:zabulon skipper
Count:-1
Comment:lets try this
Sorry, no negative animals allowed.
Command list: 

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:o
Enter name of file to read:thisfilenamedoesnotexist.dat
ERROR: File thisfilenamedoesnotexist.dat does not exists.
Command list: 

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:q
Bye bye.

This homework is due Tuesday, November 10 @noon.

Thursday, October 29, 2009

Lab test 2 review

Today we will have review for lab test 2. No lab assignment.

Section 005: Lab test 2 sample codes

public class Drink 
{
 private String name;
 private String brand;
 private double calories;
 
 public Drink()
 {
  name = "";
  brand = "";
  calories = 0;
 }
 
 public void setName(String s)
 {
  name = s;
 }
 
 public String getName()
 {
  return name;
 }
 
 public void setBrand(String s)
 {
  brand = s;
 }
 
 public String getBrand()
 {
  return brand;
 }
 
 public void setCal(double i)
 {
  calories = i;
 }
 
 public double getCal()
 {
  return calories;
 }
 
 public void printInfo()
 {
  System.out.println("Name: " + name);
  System.out.println("Brand: " + brand);
  System.out.println("Calories: " + calories);
 }

}

public class FruitJuice extends Drink 
{
 private double fruitPercentage;
 private String fruit;
 
 public FruitJuice()
 {
  super();
  fruitPercentage = 0;
  fruit = "";
 }
 
 public void setFruitPercentage(double fruit)
 {
  fruitPercentage = fruit;
 }
 
 public double getFruitPercentage()
 {
  return fruitPercentage;
 }
 
 public void setFruit(String s)
 {
  fruit = s;
 }
 
 public String getFruit()
 {
  return fruit;
 }
 
 public void printInfo()
 {
  super.printInfo();
  System.out.println("Fruit Percentage: " + fruitPercentage + "%");
  System.out.println("Fruit: " + fruit);
 }
 
}

public class Soda extends Drink 
{
 private double caffinePercent;
 
 public Soda()
 {
  super();
  caffinePercent = 0;
 }
 
 public void setCaffinePercent(double caffine)
 {
  caffinePercent = caffine;
 }
 
 public double getCaffinePercent()
 {
  return caffinePercent;
 }
 
 public void printInfo()
 {
  super.printInfo();
  System.out.println("Caffine Percent: " + caffinePercent + "%");
 }
 
}

import java.util.Scanner;

public class DrinkList
{

 public static String lowestCalorie(Drink[] drinks)
 {
  Drink drink = drinks[0];

  for(int i = 0; i < drinks.length; i++)
  {
   if(drinks[i].getCal() <= drink.getCal())
   {
    drink = drinks[i];
   }
  }

  String lowest = drink.getName();
  return lowest;
 }

 public static void printAll(Drink[] drinks)
 {
  for(int i = 0; i < drinks.length; i++)
  {
   drinks[i].printInfo();
   System.out.println();
  }
 }


 public static void main(String[] args) 
 {
  Scanner keyboard = new Scanner(System.in);

  boolean run = true;

  System.out.println("How many drinks will you be entering?");
  int num = keyboard.nextInt();
  System.out.println();

  Drink[] drinks = new Drink[num];

  for(int i = 1; i <= num; i++)
  {
   keyboard.nextLine();

   System.out.println("Information on Drink " + i + ": ");

   System.out.print("Type of Drink (Soda or Fruit) ");
   String type = keyboard.nextLine();

   System.out.print("Enter " + type + "'s name: ");
   String name = keyboard.nextLine();

   System.out.print("Enter " + name + "'s brand: ");
   String brand = keyboard.nextLine();

   System.out.print("Enter " + name + "'s calories: ");
   double calories = keyboard.nextDouble();
   keyboard.nextLine();

   if(type.equalsIgnoreCase("Soda"))
   {
    System.out.print("Enter the percentage of caffine in " + name + ": ");
    double caffine = keyboard.nextDouble();

    Soda soda = new Soda();

    soda.setName(name);
    soda.setBrand(brand);
    soda.setCal(calories);
    soda.setCaffinePercent(caffine);

    drinks[i - 1] = soda;

   }
   else if(type.equalsIgnoreCase("Fruit"))
   {
    System.out.print("Enter the fruit in " + name + ": ");
    String fruit = keyboard.nextLine();

    System.out.print("Enter the  percentage vitamin (Daily value) in " + name + ": ");
    double vitamin = keyboard.nextDouble();

    FruitJuice juice = new FruitJuice();

    juice.setName(name);
    juice.setBrand(brand);
    juice.setCal(calories);
    juice.setFruit(fruit);
    juice.setFruitPercentage(vitamin);

    drinks[i - 1] = juice;

   }
   else
   {
    System.out.println("Sorry, but I didn't recognize the kind of drink.");
    System.out.println("Next time put the type in right.");
    i--;
   }

   System.out.println();
  }
  
  String option = keyboard.nextLine();

  do
  {   
   System.out.println("Enter choice (\"Lowest Calorie\", \"PrintAll\", or \"exit\" ): ");
   option = keyboard.nextLine();

   
   if(option.equalsIgnoreCase("Lowest Calorie"))
   {
    System.out.println(lowestCalorie(drinks));
   }
   else if(option.equalsIgnoreCase("PrintAll"))
   {
    printAll(drinks);
   }
   else
   {
    System.out.println("Please enter one of the available commands.");
   }


  }while(!option.equalsIgnoreCase("Exit"));

  System.out.println("Thanks for using the program. :)");

 }

}

Chapter 9 Lecture

Below is the screencast for Chapter 9 which covers Exceptions. Most modern object-oriented programming languages (Java, C++, C#) implement exceptions. Creating Exceptions for the short programs you write in class is a bit of an overkill. Still, Exceptions are very useful in large programs.

CSCE 145: Chapter 9 from Jose Vidal on Vimeo.

Below are the textbook slides for this chapter.
You must have watched this screencast by Tuesday, November 3.

Tuesday, October 27, 2009

Test 2


Here is our second test along with the answers to each question:
  1. (20%) The following program

      public static void main (String[] args){
        //create animal with name "bunny" and weight of 10
        Animal bunny = new Animal("bunny", 10);
        Animal fox = new Animal();
        System.out.println(fox);
        System.out.println(bunny);
        bunny.feed(4);
        System.out.println(bunny);
        
      }
    
    prints out the following when run (every println in the code above corresponds to one line below):

    name: weight:-1
    name:bunny weight:10
    name:bunny weight:14
    
    Implement the missing Animal class so that it works as shown.



    Answer:
    public class Animal {
    
      private String name;
    
      private int weight;
    
      public Animal (){
        name = "";
        weight = -1;
      };
    
      public Animal (String n, int w){
        name = n;
        weight = w;
      }
      
      public String toString(){
        String result = "name:" + name + " weight:" + weight;
        return result;
      }
    
      public void feed(int amount){
        weight += amount;
      }
    
    }
    


  2. (20%) What does the following program print out when run?

    public class Counter {
    
      public static int alpha;
    
      public int beta;
    
      public Counter (){
        alpha = 5;
        beta = 10;
      }
    
      public void increase() {
        alpha = alpha + 1;
        beta = beta + 1;
      }
    
      public String toString() {
        return "alpha=" + alpha +"  beta=" + beta;
      }
    
      public static void main(String[] args){
        Counter x = new Counter();
        Counter y = new Counter();
        System.out.println(x);
        System.out.println(y);
        x.increase();
        System.out.println(x);
        System.out.println(y);
        Counter z = new Counter();
        System.out.println(z);
        System.out.println(x);
      }
    
    }
    
    Answer:
    alpha=5  beta=10
    alpha=5  beta=10
    alpha=6  beta=11
    alpha=6  beta=10
    alpha=5  beta=10
    alpha=5  beta=11
    
    


  3. (20%) In the game of chess the rook can capture other pieces that are in his same row or in his same column. Implement a function which, given a 2-dimensional array of integers and a row and column position, returns true if there are any non-zero numbers on the same row or on the same column. For example, the following program:

    public class Rook {
    
      public static void main(String[] args){
        int[][] board = new int[8][8];
        for (int i=0; i < 8; i++){
          int[] col = {0,0,0,0,0,0,0,0}; 
          board[i] = col;
        }
    
        board[1][5] = 1;
        
        //root has a kill if there is a non-zero number anywhere in row 1, or in column 2.
        if (rookCanKill(board,1,2))
          System.out.println("Root has kill at 1,2");
        else
          System.out.println("Root cannot kill at 1,2");
    
    
        //root has a kill if there is a non-zero number anywhere in row 2, or in column 2.
        if (rookCanKill(board,2,2))
          System.out.println("Root has kill at 2,2");
        else
          System.out.println("Root cannot kill at 2,2");
      }
    
    
    }
    
    prints out:

    Root has kill at 1,2
    Root cannot kill at 2,2
    
    Implement the public static boolean rookCanKill(int[][] board, int row, int col) function.



    Answer:
      public static boolean rookCanKill(int[][] board, int x, int y){
        for (int i=0; i < board.length; i++)
          if (board[x][i] != 0) return true;
        for (int i=0; i < board.length; i++)
          if (board[i][y] != 0) return true;
        return false;
      }
    
    


  4. (20%) What does the following program print out when we run its main?

    public class A {
    
      public A (){
        System.out.println("Creating A");
      }
    
      public void talk (){
        System.out.println("I am A!");
      }
    
      public void whine(){
        System.out.println("I am Always last.");
      }
    
      public void whine(int x){
        System.out.println("Am I late?");
      }
    
    }
    
    public class B extends A{
    
      public B (){
        System.out.println("Creating B");
      }
    
      public void talk (){
        System.out.println("I am B!");
      }
    
      public void whine(){
        System.out.println("I am Bored.");
      }
    
    }
    
    public class C extends B{
    
      public C (){
        System.out.println("Creating C");
      }
    
      public void talk (){
        System.out.println("I am C!");
      }
    
      public void whine(){
        System.out.println("I am Cursed.");
        super.whine();
      }
    
      public void whine(int x){
        System.out.println("I am Crazy.");
        whine();
      }
    
      public static void main(String[] args){
        C c = new C();
        c.talk();
        c.whine();
        B b = (B) c;
        b.talk();
        b = new B();
        b.whine();
      }
    
    }
    
    Answer:
    Creating A
    Creating B
    Creating C
    I am C!
    I am Cursed.
    I am Bored.
    I am C!
    Creating A
    Creating B
    I am Bored.
    


  5. (20%) Write some code which creates an array and populates it with the day of the month for all the days of a non-leap year. That is, given that the months have the following number of days:


    Month
    Days
    January
    31
    February
    28
    March
    31
    April
    30
    May
    31
    June
    30
    July
    31
    August
    31
    September
    30
    October
    31
    November
    30
    December
    31

    you will create an array dayNumber which has the number of the day of the month for each day of the year, as such:

    dayNumber[0] = 1
    dayNumber[1] = 2
              :
    dayNumber[30] = 31
    dayNumber[31] = 1  //February first
    dayNumber[32] = 2
              :
    dayNumber[58] = 28
    dayNumber[59] = 1
              :
              :
    dayNumber[364] = 31
    
    You will not receive credit for writing down 365 assignment statements, or for writing an array literal with each of the 365 values in it. You should use a for-loop. Hint: use an array literal to store the number of days in each month.

    Answer:
    public class Days{
    
      public static void main(String[] args){
        int[] dayNumber = new int[365];
        int[] daysInMonth = {31,28,31,30,31,30,31,31,30,31,30,31};
        int day = 1;
        int month = 0;
        int i = 0;
        while (month < daysInMonth.length){
          dayNumber[i] = day;
          i++;
          day++;
          if (day > daysInMonth[month]){
            day = 1;
            month++;
          }
        }
        //print it out
        for (i=0;i<dayNumber.length;i++)
          System.out.println(i + " " + dayNumber[i]);
      }
    
    }
    


The grade distribution for this test is shown in the graph below.




Lab test 2 for Section 006

Write a program that basically simulates a poker game.

You need to implement:

Card class

type: spades, diamond, club, heart

value: A, 2, 3, ..., J, Q, K (you can use 1 to 13)

a constructor to set the type and value

getType, getValue

CompareTo(Card anotherCard)

// compare the value first

// if they are equal, compare the type(spades > diamond > club > heart)

toString() // type and value in the range 1 to 13 if you use integer

Player class

player's name

an array of 5 cards

giveCard(Card p) // give a card to this player

getMaxIndex() // get the index of the maximum card

getCardByIndex(int i) // get cards[i]

toString()

PokerGame class

Test your previous two classes. There is no extra credits for those who write a friendly UI using Scanner class.

1. Create a set of cards(52 cards without joker, use loop to assign the values and types)

2. Create 2 players

3. Give each player 5 cards randomly, print out the cards of each player by calling toString()

4. Get the max card of each player and compare

Hints:

1. You may use an array of 52 length to mark if the corresponding card is given out.

2. Use the following code to generate a random number if you need.

Random rand = new Random();

int num = rand.nextInt(10); // returns a integer from 0 to 9

System.out.println((num+1));

You can add more data members and methods in your classes if you think they are helpful. But you may lose credits if they are harmful to your structure of the class.

Please send your program to xusun09@gmail.com no later than 6:00pm today, and use "CSCE145-LABTEST2-NAME" as the subject.

Lab test 02 for Section 005

The Drink.java class is the super class. It has set and get methods for the attributes name, brand, calories. The Soda and FruitJuice classes inherit the Drink class. The soda class has attributes caffeine percentage. The FruitJuice has attributes vitaminPercentage and fruit. Add a printInfo method in the Drink class and then override that method in the subclasses.

The DrinkList.java will contain your main method, which is where you will declare your array of Drink items, and control execution. In addition, the DrinkList class has 2 methods:

1) printDrinkWithLowestCalories (Drink[] drink) searches the array for the drink with Lowest calories and prints it's name and brand.

2) printAll(Drink[] drink prints the information of all (this includes Soda and FruitJuice information) drinks stored in the array.

here is the sample output:

Please enter the number of drinks to be read: 2

Data For Drink 1:

Type of Drink (Soda/Fruit)? Soda

Enter Soda's name: Sierra Mist

Enter Sierra Mist's brand: Pepsi Co

Enter calories for Sierra Mist: 150

Enter percentage caffeine for Sierra Mist : 0

Data For Drink 2:

Type of Drink (Soda/Fruit)? Fruit

Enter Name: Orange juice

Enter the brand name of Orange Juice: Tropicana

Enter calories of Tropicana: 240

Enter Tropicana's fruit: Orange

Enter Tropicana's percentage vitamin (Daily value): 100

Enter choice ("Low Calorie" or "PrintAll" or "exit" ): Low Calorie

Sierra Mist

Enter choice ("Low Calorie" or "Brand" or "exit" ): exit

Thank you for using the program.

HINT: declare printAll(Drink[] drink) as static method in DrinkList class like this:

public static void/String printAll(Drink[] drink)

NOTE: submit your program before 4:00pm to espiggy@gmail.com. NO late submittion accepted!!

Monday, October 26, 2009

ACM Fall Brawl


Our ACM student chapter (you should join, if you are a Computer major) is holding their annual Fall Brawl: a fighting videogame tournament. It is only $5 to participate and there will be prizes.

Thursday, October 22, 2009

Sudoku Example from Class

You will probably need some extra time to digest the example I did in class, so I am posting it here. It successfully ran two test cases so it must be correct, of course (NOT).

public class Sudoku {
 
 /** 0 means box is blank, otherwise only numbers 1..9 are allowed */
 private int[][] board = new int[9][9];
 
 public Sudoku(){
  board[0][0] = 1;
//  board[0][1] = 1;
  
 }
 
 /** @return true if theBoard[rowoffset..rowoffset+2][coloffset..coloffset+2]
  * does not contain more than one copy of 1..9. That is, if the 3x3
  * box is a legal subbox
  */
 private boolean isLegalBox(int[][] theBoard, int rowOffset, int colOffset){
  boolean[] check = new boolean[10];
  for (int row = rowOffset; row < rowOffset + 3; row++){
   for (int col =colOffset; col < colOffset + 3; col++){
    if (board[row][col] == 0)
     continue;
    if (check[ board[row][col] ])
     return false;
    else
     check[ board[row][col] ] = true;
   }
  }
  return true;
 }
 
 public boolean isLegalBoard(int [][] theBoard){
  
  //check all rows
  for (int row = 0; row < 9; row++){
   boolean[] check = new boolean[10];
   for (int i =0; i < 10; i++)
    check[i] = false;
   for (int col =0; col < 9; col++){
    if (board[row][col] == 0)
     continue;
    if (check[ board[row][col] ])
     return false;
    else
     check[ board[row][col] ] = true;
   }
  }
  
  //check all columns
  for (int col = 0; col < 9; col++){
   boolean[] check = new boolean[10];
   for (int i =0; i < 10; i++)
    check[i] = false;
   for (int row =0; row < 9; row++){
    if (board[row][col] == 0)
     continue;
    if (check[ board[row][col] ])
     return false;
    else
     check[ board[row][col] ] = true;
   }
  }

  //check all 9 boxes
  for (int row = 0; row < 9; row+=3){
   for (int col =0; col < 9; col+=3){
    if (! isLegalBox(theBoard, row, col))
     return false;
   }
  }
  
  return true;
 }
 
 public boolean isLegal(){
  return isLegalBoard(board);
 }
 
 public String toString(){
  String result = "";
  for (int row = 0; row < 9; row++){
   for (int col =0; col < 9; col++){
    result += Integer.toString(board[row][col]) + " ";
   }
   result += "\n";
  }
  return result;
 }
}



Lab 16

Define a Class named Product whose objects are records for a department. A Product has the id number (use type String). Define a Class named Book. Derive this class from Product. You can define the attributes of Book. For example, A Book object has the id (defined in Product class), the book name (use type String) and the price (use type double). Define another Class named Shirt. Derive this class from Product. Define the attributes of Shirt. For example, A Shirt object has the id (defined in Product class), the color (use type String), and the size (use type String). Give your classes a reasonable complement of constructions and accessor methods, and a toString() methods which can display the infomation of product in the cart.

Define a Class named Cart whose objects are records for customer. A customer has the contents which is the array of Product in the cart. Give your classes a reasonable complement of constructions and accessor methods, a add mothods with product object as parameter which can add the product to your cart (the array of product), and a toString() methods which can display the infomation of all product in the cart

Tuesday, October 20, 2009

Monday, October 19, 2009

HW5 example

// FifteenPuzzle.java
public class FifteenPuzzle {
 private int[][] board;
 private int blank_x;
 private int blank_y;
 
 public FifteenPuzzle()
 {
  this.board = new int[4][4];
  int num = 1;
  for (int i=0; i<4; ++i)
   for (int j=0; j<4; ++j)
   {
    this.board[i][j] = num++;
   }
  this.blank_x = 3;
  this.blank_y = 3;
 }
 
 public String toString()
 {
  String strBoard="";
  for (int i=0; i<4; ++i)
  {
   for (int j=0; j<4; ++j)
   {
    if (this.board[i][j]==16)
     strBoard += "   ";
    else
     strBoard += String.format("%3d",this.board[i][j]);
   }
   strBoard += "\n";
  }
  return strBoard;
 }
 
 public boolean moveUp()
 {
  if (this.blank_x>0)
  {
   int temp = this.board[blank_x][blank_y];
   this.board[blank_x][blank_y]=this.board[blank_x-1][blank_y];
   this.board[blank_x-1][blank_y]=temp;
   this.blank_x--;
   return true;
  }
  return false;
 }
 
 public boolean moveDown()
 {
  if (this.blank_x<3)
  {
   int temp = this.board[blank_x][blank_y];
   this.board[blank_x][blank_y]=this.board[blank_x+1][blank_y];
   this.board[blank_x+1][blank_y]=temp;
   this.blank_x++;
   return true;
  }
  return false;
 }
 
 public boolean moveLeft()
 {
  if (this.blank_y>0)
  {
   int temp = this.board[blank_x][blank_y];
   this.board[blank_x][blank_y]=this.board[blank_x][blank_y-1];
   this.board[blank_x][blank_y-1]=temp;
   this.blank_y--;
   return true;
  }
  return false;
 }
 
 public boolean moveRight()
 {
  if (this.blank_y<3)
  {
   int temp = this.board[blank_x][blank_y];
   this.board[blank_x][blank_y]=this.board[blank_x][blank_y+1];
   this.board[blank_x][blank_y+1]=temp;
   this.blank_y++;
   return true;
  }
  return false;
 }
 
 public boolean isWinner()
 {
  int num = 1;
  for (int i=0; i<4; ++i)
   for (int j=0; j<4; ++j)
   {
    if (this.board[i][j] != num++)
     return false;
   }
  return true;
 }
}




// Demo.java
// report bugs to xusun09@gmail.com

import java.util.Scanner;
public class Demo {

 public static void main(String[] args) {
  Scanner reader = new Scanner(System.in);
  FifteenPuzzle fp = new FifteenPuzzle();
  
  System.out.println(fp.toString());
  System.out.println("Enter command or 'done' to finish");
  
  while(true)
  {
   System.out.print("Enter command (u,d,l,r):");
   String command = reader.nextLine().toLowerCase();
   if (command.equals("u"))
    fp.moveUp();
   else if (command.equals("d"))
    fp.moveDown();
   else if (command.equals("l"))
    fp.moveLeft();
   else if (command.equals("r"))
    fp.moveRight();
   else if (command.equals("done"))
    break;
   System.out.println(fp.toString());
   if (fp.isWinner())
    System.out.println("WINNING BOARD!!\n");
  }
 }
}

Thursday, October 15, 2009

Homework 6: Media Library


For this homework you will implement a series of Java classes which are meant to be at the heart of a media library program (like iTunes). The diagram above is a UML diagram. Your textbook explains these diagrams in detail starting in page 559. You will implement all the classes described in the above diagram along with their respective attributes and methods
There are some some further requirements:
  1. Each of the leaf classes must implement a toString that adds all the information particular to that class to the string, and that calls the parent toString method to get the common parts. For example, only movies have a rating but all media has a title.
  2. Every class should have two constructors (these are not shown in the UML diagram): one that takes no arguments and sets values to the empty string, 0, or equivalent, and one that takes all the arguments for that class. Constructors should call the parent constructor when appropriate.
  3. The movie ratings are only one of:G, PG, PG-13, R, NC-17, X. You must implement set/get methods to ensure no one can set the rating to something else.
  4. The equals method in Media only test that the titles are the same, but the one in Song also tests that the artists are the same.
  5. You must also write a main method that tests all your classes and their methods.
This homework is due by noon on Thursday, October 22.

Lab 14

Question 4 on page 608.

Tuesday, October 13, 2009

Monday, October 12, 2009

HW4 example

// Vector.java
public class Vector {
 private double dx,dy;
 
 public Vector(double _x, double _y)
 {
  this.dx = _x;
  this.dy = _y;
 }
 public void addVector(Vector otherVector)
 {
  this.dx += otherVector.dx;
  this.dy += otherVector.dy;
 }
 public void subtractVector(Vector otherVector)
 {
  this.dx -= otherVector.dx;
  this.dy -= otherVector.dy;
 }
 public void multiply(int a)
 {
  this.dx *= a;
  this.dy *= a;
 }
 public double getMagnitude()
 {
  return Math.sqrt(dx*dx+dy*dy);
 }
 public void normalize()
 {
  double magnitude = getMagnitude();
  if (magnitude==0)
   return;
  this.dx /= magnitude;
  this.dy /= magnitude;
 }
 public String toString()
 {
  return ("("+Double.toString(this.dx)+", "+Double.toString(this.dy)+")");
 }
 
}



//VectorDemo.java
public class VectorDemo {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Vector v1 = new Vector(3,4);
  System.out.println(v1.toString());
  v1.multiply(3);
  System.out.println(v1.toString());
  Vector v2 = new Vector(6, 8);
  v1.subtractVector(v2);
  System.out.println(v1.toString());
  v1.normalize();
  System.out.println(v1.toString());
 }

}

Tuesday, October 6, 2009

Homework 5: The Fifteen Puzzle

In the fifteen puzzle you are given a board with embedded tiles, numbered 1 to 15, which can only be moved up, down, left, or right to occupy the one blank spot. That is, you can only move a tile that is a neighbor of the blank spot. Another way of looking at it is to say that you can only move the blank spot up, down, left or right, exchanging it with the tile that is already in that position.

For this homework you will implement a FifteenPuzzle class that has the following methods:

  1. A constructor that initializes the board to the solved position, with the blank on the bottom left, as shown in the figure.
  2. A toString() method which prints a pretty board, like the ones shown below.
  3. The methods moveUp, moveDown, moveLeft, and moveRight which move the empty space up, down, left, and right, respectively. The functions should do nothing if called with a board configuration that would make it impossible to execute the action. For example, if the space is in the bottom right and we ask it to moveDown it should stay there. The program should not crash.
  4. The method isWinner which returns true if the board is in its initial configuration.

You will also implement a main function that asks the user which way he would like to move the tile and then performs the move, by calling one of the moveX methods, and displays the new board. Below is a sample interaction with the program:

 1  2  3  4 
 5  6  7  8 
 9 10 11 12 
13 14 15    

Enter command or 'done' to finish
Enter command (u,d,l,r):u
 1  2  3  4 
 5  6  7  8 
 9 10 11    
13 14 15 12 

Enter command (u,d,l,r):r
 1  2  3  4 
 5  6  7  8 
 9 10 11    
13 14 15 12 

Enter command (u,d,l,r):l
 1  2  3  4 
 5  6  7  8 
 9 10    11 
13 14 15 12 

Enter command (u,d,l,r):r
 1  2  3  4 
 5  6  7  8 
 9 10 11    
13 14 15 12 

Enter command (u,d,l,r):d
 1  2  3  4 
 5  6  7  8 
 9 10 11 12 
13 14 15    

WINNING BOARD!!

Enter command (u,d,l,r):l
 1  2  3  4 
 5  6  7  8 
 9 10 11 12 
13 14    15 

Enter command (u,d,l,r):l
 1  2  3  4 
 5  6  7  8 
 9 10 11 12 
13    14 15 

Enter command (u,d,l,r):u
 1  2  3  4 
 5  6  7  8 
 9    11 12 
13 10 14 15 

Enter command (u,d,l,r):u
 1  2  3  4 
 5     7  8 
 9  6 11 12 
13 10 14 15 

Enter command (u,d,l,r):r
 1  2  3  4 
 5  7     8 
 9  6 11 12 
13 10 14 15 

Enter command (u,d,l,r):d
 1  2  3  4 
 5  7 11  8 
 9  6    12 
13 10 14 15 

Enter command (u,d,l,r):done

You must use a 2-dimensional array to implement the board. This homework is due by Thursday, October 15 @ noon.

Tip: To turn an integer into a string that is padded on the left with enough spaces to ensure it is of length at least 3, use String iAsPaddedString = String.format("%3d",i); where i is the integer.

For hackers only: write a method that solves the puzzle. A good way to do it is using the A-star algorithm. You will learn all about this and other search algorithms if you take our Artificial Intelligence class (CSCE 580)

Chapter 8 Lecture

Below is the screencast for Chapter 8 which covers inheritance and polymorphism. Both of these are features that every object-oriented programming language implements. They help one minimize the number of methods that your program must define. They are overkill for the small programs we will be writing in this class but are indispensable for managing real-world software which is always much larger. You must have watched this screencast by Tuesday, October 13.

CSCE 145: Chapter 8 from Jose Vidal on Vimeo.

Also, here are the slides from the textbook.

Lab 12

Quesiton 1 on page 529.

Have fun!

NOTE: For section 005 (the 2pm section), today's lab has been moved from B205 to Swearingen 1D29 !!!!

Friday, October 2, 2009

Chapter 7 Lecture

Below is the screencast for Chapter 7, which you must have watched by Tuesday, October 6. This chapter intoduces the topic of arrays which are variables that can hold an array of different values. All programming languages have arrays.

CSCE 145: Chapter 7 from Jose Vidal on Vimeo.

Here are the textbook slides for this chapter.

Thursday, October 1, 2009