Thursday, September 30, 2010

HW 4: Colors

For this homework you will implement a simple Color class which stores RGB colors prints them out and lets you mix colors.

Your program will have the constructors and methods such that this main:

 public static void main(String[] args) {
  //a constructor with all ints arguments, each is a number between 0 and 255.
  Color red = new Color(255,0,0);
  System.out.println(red);
  
  //a constructor that understands "red", "green" and "blue".
  Color blue = new Color("blue");
  System.out.println(blue);
  //a constructor with all doubles as arguments, each is a number between 0 and 1.
  Color green = new Color(0.0, 1.0, 0.0);
  System.out.println(green);
  //if a number is out of range you push it back into the range!
  Color reallyGreen = new Color(0.0, 100, 0.0);
  System.out.println(reallyGreen);
  
  //Mix colors by simply taking the average of each component (RGB).
  Color purple = red.mixWith(blue);
  System.out.println("purple=" + purple);
  purple = purple.mixWith(red);
  System.out.println(purple);
  purple = purple.mixWith(red);
  System.out.println(purple); 
 }
prints out these statements:
#ff0000
#0000ff
#00ff00
#00ff00
purple=#7f007f
#bf003f
#df001f

Those are hexadecimal numbers there, in the standard Hex triplet format. Notice how your code will not let the user create an illegal color.

Tip: your internal representation should use a number between 0 and 255 for each one of the channels (RGB). Also, try to make use of your own private methods.

The homework should be deposited in our dropbox by Thursday, October 7 @ 9am

Lab 11 - Section 6 - Double Class

Write a class called Double, which has one instance variable d of type double and has the following methods:

(1) A default constructor: Double() which sets d to 0
(2) Another constructor: Double(double initialValue) which sets d to initialValue
(3) add(double d1): adds d1 to d and returns the result
(4) subtract(double d1): subtracts d1 from d and returns the result
(5) multiply(double d1): multiply d1 with d and returns the result
(6) divide(double d1): divide d by d1 and returns the result. The division should be done when d1 != 0 else print error message

You can add some more methods, which can be applied to double. For example, you can find the absolute value of the double d.

When you are done, submit your program in the (dropbox) https://dropbox.cse.sc.edu/ and also get it checked.

Lab 11 -- Section 5 -- Person's Class with Constructors

Problem 3 -- Page 434

Test 1 Grades

Wednesday, September 29, 2010

Speak Like a Professional Developer

Every scientific field has its own vocabulary, composed of the special words it uses to define things that are only of interest to those in the field. For example, when watching a hospital show on TV you get to hear stuff like "he's in hypocardiac messenterporary rhythm" which non-medical people don't understand (ok, I made that one up).

Software development also has those special words but, annoyingly, the words we use are words that already have a meaning in English. We just give them a different, very specific, meaning. As a developer you will need to learn these words since they are used in both conversation and in writing (that API you are trying to understand).

Below are some examples from the last test. These terms are defined in the book, look them up if you can't remember what they mean:

  • scope - Sample usage: "Variable X cannot be used outside its scope". You don't say: "X is a local variable within the loop", or "X has no meaning in line 12"
  • argument - Sample usage: "Method setName takes two arguments". You don't say: "Method setName takes two inputs", or "Method setName is filled in with two variables"
  • type - Sample usage: "X and Y are of different types". You don't say: "X is used as a String and Y is used as an int"
  • declared vs initialized - these are different. Do not confuse them.

And, no, I do not take points off for this, as long as I know what you mean its OK. Still, you should learn to talk the talk.

Tuesday, September 28, 2010

Lab Test 1- Section 6 - Shopping card

Write a java program which will simulate a "shopping card". Here is a sample interaction of the program:
>Welcome! Enjoy shopping! We sell a Shirt at $15, a pair of Shoes at $30 and a Hat at $5.
>What do you want to buy (enter "done" to quit)?
>shirt
>You are carrying 1 Shirt.
>What do you want to buy (enter "done" to quit)?
>Shoe
>You are carrying 1 shirt and 1 pair of shoes.
>What do you want to buy (enter "done" to quit)?
>Shirt
>You are carrying 2 shirt and 1 pair of shoes.
>What do you want to buy (enter "done" to quit)?
>Hat
>You are carrying 2 shirt, 1 pair of shoes, 1 Hat.
>done
>Your total bill is $65
>Goodbye
Your program should take the following inputs:
  1. If you want to buy a shirt, give input as: Shirt
  2. If you want to buy a pair of shoes, give input as: shoe
  3. If you want to buy a hat, give input as: hat
  4. If you want to quit the program: done
When you are done, submit your program in the dropbox.

LabTest 1 -- GRID WALK SEARCH

3 OBJECTS ARE PLACE IN A 6*6 GRID. The Initial Starting Position of a Man is (0,0). Walk the GRID to find the Objects : Heres a sample output :
--------------------------
Welcome to THE GRID SEARCH GAME: Walk to Find Objects:
OBJECTS ARE PLACED AT:
Square Object PLaced at(x,y): (5,5)
Circle Object Placed at(x,y): (3,4)
Rectangular Object Placed at(x,y): (2,3)
Starting Position: (0,0)

Enter Direction(North/South/East/West/NorthEast/NorthWest/SouthEast/SouthWest) or 'Done' to End :
northeast
CurrentPosition(x,y): (1,1)

Enter Direction(North/South/East/West/NorthEast/NorthWest/SouthEast/SouthWest) or 'Done' to End :
northeast
CurrentPosition(x,y): (2,2)

Enter Direction(North/South/East/West/NorthEast/NorthWest/SouthEast/SouthWest) or 'Done' to End :
northeast
CurrentPosition(x,y): (3,3)

Enter Direction(North/South/East/West/NorthEast/NorthWest/SouthEast/SouthWest) or 'Done' to End :
northeast
CurrentPosition(x,y): (4,4)

Enter Direction(North/South/East/West/NorthEast/NorthWest/SouthEast/SouthWest) or 'Done' to End :
northeast
CurrentPosition(x,y): (5,5)
Square Object Encountered

Enter Direction(North/South/East/West/NorthEast/NorthWest/SouthEast/SouthWest) or 'Done' to End :
northeast
CurrentPosition(x,y): (0,0)

Enter Direction(North/South/East/West/NorthEast/NorthWest/SouthEast/SouthWest) or 'Done' to End :
west
CurrentPosition(x,y): (5,0)

Enter Direction(North/South/East/West/NorthEast/NorthWest/SouthEast/SouthWest) or 'Done' to End :
south
CurrentPosition(x,y): (5,5)
Square Object Encountered

Enter Direction(North/South/East/West/NorthEast/NorthWest/SouthEast/SouthWest) or 'Done' to End :
southwest
CurrentPosition(x,y): (4,4)

Enter Direction(North/South/East/West/NorthEast/NorthWest/SouthEast/SouthWest) or 'Done' to End :
west
CurrentPosition(x,y): (3,4)
Circle Object Encountered

Enter Direction(North/South/East/West/NorthEast/NorthWest/SouthEast/SouthWest) or 'Done' to End :
west
CurrentPosition(x,y): (2,4)

Enter Direction(North/South/East/West/NorthEast/NorthWest/SouthEast/SouthWest) or 'Done' to End :
south
CurrentPosition(x,y): (2,3)
Rectangular Object Encountered

Enter Direction(North/South/East/West/NorthEast/NorthWest/SouthEast/SouthWest) or 'Done' to End :
north
CurrentPosition(x,y): (2,4)

Enter Direction(North/South/East/West/NorthEast/NorthWest/SouthEast/SouthWest) or 'Done' to End :
north
CurrentPosition(x,y): (2,5)

Enter Direction(North/South/East/West/NorthEast/NorthWest/SouthEast/SouthWest) or 'Done' to End :
north
CurrentPosition(x,y): (2,0)

Enter Direction(North/South/East/West/NorthEast/NorthWest/SouthEast/SouthWest) or 'Done' to End :
southwest
CurrentPosition(x,y): (1,5)

Enter Direction(North/South/East/West/NorthEast/NorthWest/SouthEast/SouthWest) or 'Done' to End :
done
Done

Test 1 Solution

  1. (10%) The following program fails to compile. Why does it fail to compile?
    public class Broken {
    
      public static void main(String[] args) {
        for (int i = 0; i < 10; i++){
          int result = 0;
          result = result + 1;
        }
        System.out.println(result);
      }
    
    }
    
    Answer: The variable result is used outside its scope, by the println statement.
  2. (10%) The following program also fails to compile. Why does it fail to compile?
    import java.util.Scanner;
    
    public class BrokenA {
      static final double RATE = 0.5;
    
      public double nextYear(double x) {
        return x * RATE;
      }
    
      private static void main(String[] args) {
        int x = 0;
        String name = "Steve";
        Scanner keyboard = new Scanner(System.in);
        String value = keyboard.next();
        BrokenA  ba = new BrokenA();  
        double r = ba.nextYear(value);
        System.out.println(r);
      }
    }
    
    
    Answer:The method nextYear takes a double as an arugment but we are giving it a String.
  3. (30%) What does the following program print out:
    public class RPS {
    
      public static void main(String[] args) {
        String p1 = "PPPSSSRRRPPP"; //notice, only 3 letters used
        String p2 = "RSPPSRPSRPSP";
        for (int i=0; i < p1.length(); i++){
          char c1 = p1.charAt(i);
          char c2 = p2.charAt(i);
          System.out.print (c1 + " " + c2 + " ");
          if (c1 == c2) {
            System.out.println("=");
          }
          else switch (c1) {
          case 'R':
            System.out.println((c2 == 'S') ? 1 : 2);
            break;
          case 'P':
            System.out.println((c2 == 'S') ? 2 : 1);
            break;
          case 'S':
            System.out.println((c2 == 'P') ? 1 : 2);
            break;
          };
        }
      }
    }
    
    Answer:
    P R 1
    P S 2
    P P =
    S P 1
    S S =
    S R 2
    R P 2
    R S 1
    R R =
    P P =
    P S 2
    P P =
    

    Its the game of rock-paper-scissors (RPS).

  4. (50%) Write a program that:
    1. Asks the user for an integer. Assume he does enter an integer. If he enters 0 then the program stops.
    2. Otherwise, if it is a negative integer then the program converts to its positive counterpart (for example, -5 turns into 5).
    3. Otherwise, determine if there are two positive integers X and Y such that the number the user typed is equal to 3*X + 7*Y. If there are, print them, if not then print NONE FOUND. You will do this by brute-force: examine all realistic combinations of possible values of X and Y. (HINT: both of these will always be positive and smaller than...)
    Below is a sample interaction with the program. The users' inputs are in boldface:
    Enter number:3
    3= 3*1 + 7*0
    Enter number:-3
    3= 3*1 + 7*0
    Enter number:5
    NOT FOUND
    Enter number:7
    7= 3*0 + 7*1
    Enter number:11
    NOT FOUND
    Enter number:12
    12= 3*4 + 7*0
    Enter number:21
    21= 3*0 + 7*3
    Enter number:22
    22= 3*5 + 7*1
    Enter number:123456
    123456= 3*6 + 7*17634
    
    Answer:
    import java.util.Scanner;
    
    public class Legal {
    
      public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        while (true) {
          System.out.print("Enter number:");
          int number = keyboard.nextInt();
          if (number == 0) break;
          if (number < 0) number = number * -1;
          int x =0;
          int y =0;
          boolean found = false; //a flag
          for (x = 0; x < number; x++){ 
            for (y=0; y < number; y++){ //number is a bit high here, what should we use?
              if (number == 3*x + 7*y) {
                found = true;
                break;}
            }
            if (found) break;
          }
          if (found) {
            System.out.println(number + "= 3*" + x + " + 7*" + y);
          }
          else {
            System.out.println("NOT FOUND");
          };
        }
      }
    }
    

Chapter 6 Video

Below is the screencast for Chapter 6. In this chapter we talk about constructors, overloading, and static instance variables and member functions. All object-oriented programming languages implement concepts such as these. The goal of these is to make it easier for us to write large programs, even if it makes it a bit harder to write the tiny little programs we write in this class. You must have read chapter 6 and have watched the screencast before class on Thursday, September 30.

CSCE 145: Chapter 6 from Jose Vidal on Vimeo.

Also, below are the texbook's presenation slides for your reviewing pleasure.

Thursday, September 23, 2010

Tutoring Resources

Here are all the ways, that I know of, that you can get tutoring for 145:
  1. Setup a time with your TA.
  2. Setup a time with me, or drop by during my office hours.
  3. Setup a time with our ACM students, who have a regular 145 tutoring schedule. Just send them an email.
  4. Use supplemental instruction. Yes, I know it says "Huhns" there, but you can still go. Its the same class.
I hope others add their own resources in the comments. And, any upperclassmen reading this who would like to volunteer are greatly appreciated.

Lab Test 1 Review -- Calculator Class

Write a Calculator Class which following operations on 2 numbers:
1) Add
2) Subtract
3) Multiply
4) Divide
5) Square Root
6) Power
In the main() function:
1) Have a loop which goes on taking the operation from the user about which operation he wants to do and take input of 2 numbers for each operation.
2) If the user is done : he should type "done" and the program should shop.
3) If a non-recognized operation is input by the user the program should inform the user that the operation is in-appropriate and that the user should input again ( so the program should prompt the user again to enter operation and the 2 numbers

*********************************************************************
This program deals with :
1) Objects
2) Loop
3) if-else if-else

Tuesday, September 21, 2010

Lab 9 --section 6 --Purchase class

problem 6 - page 333

Lab09 -- Section 5 -- BasketBallGame

Problem 9 -- Page 334

HW 3 Solution

Below is my Zuckerville implementation:

import java.util.Scanner;

/** 
 * Zuckerville: a game where the only winner is the one who didn't play.
 * 
 * @author Jose M Vidal 
 *
 */

public class Zuckerville {

 public final static int TIME_TO_HARVEST = 10; //in ticks

 public final static int COST_OF_FERTILIZER = 4; //in zuckerdollars

 public static void main(String[] args) {
  int money = 5; //the amount of "money" the player starts with
  int seeds = 0;
  int plot = 0; //the number of seeds in the plot
  int timeToHarvest = 0; //the time left before the plants get harvested
  int time = 0;
  boolean isFertilized = false; //whether or not the plot has been fertilized
  Scanner keyboard = new Scanner(System.in);
  String command;
  System.out.println("Welcome to Zuckerville, where the only way to win is not to play!");
  System.out.println("We gave you $" + money + " zuckerdollars to get you started! Now go plant!"); //first one's always free
  System.out.println(""); 
  do {
   System.out.print("[" + time + " $" + money + "] Command: ");
   command = keyboard.nextLine();
   int spaceIndex = command.indexOf(' ');
   if (command.startsWith("deposit")) {
    int dollarIndex = command.indexOf('$');
    int deposit = Integer.parseInt(command.substring(dollarIndex + 1));
    money += deposit;
    System.out.println("You now have $" + money);
   }
   else if (command.startsWith("buy")) {
    int amountToBuy = Integer.parseInt(command.substring(spaceIndex + 1));
    if (amountToBuy <= money ) {
     System.out.println("You bought " + amountToBuy + " seeds.");
     seeds += amountToBuy;
     money -= amountToBuy;
    }
    else {
     System.out.println("Sorry, you don't have enough zuckerdollars.");
    }
   }
   else if (command.startsWith("plant")) {
    if (plot != 0) {
     System.out.println("Sorry, there are already seeds planted there. You must wait till after harvest.");
    }
    else {
     for (int i = 0; i < seeds; i++) {
      System.out.println("Planted a seed.");
     }
     plot = seeds;
     seeds = 0;
     timeToHarvest = TIME_TO_HARVEST;
    }
   }
   else if (command.startsWith("fertilize")) {
    if (money < COST_OF_FERTILIZER) {
     System.out.println("Sorry, it costs $" + COST_OF_FERTILIZER + " to buy fertilizer.");}
    else {
     System.out.println("You fertilized your plot!");
     isFertilized = true;
     money -= COST_OF_FERTILIZER;
    }
   }
   else if (!command.startsWith("quit")) {
    System.out.println("What did you say?");
   }
   time++;
   timeToHarvest -= (isFertilized) ? 2 : 1;
   if (timeToHarvest <= 0 && plot != 0) { //Harvest the flowers if the time has come.
    for (int i =0; i < plot; i++) {
     System.out.println("You harvested a beautiful flower.");
    }
    isFertilized = false; //easy to forget this one
    plot = 0;
   }
  } while (!command.equals("quit"));
  System.out.println("Goodbye!");
 }
}

Thursday, September 16, 2010

Lab 8 - section 6

Develop and implement a class Student that represents a University Student. A Student object should have four attributes: the name of the student, the DOB of the student, the name of the university where the student is studying and height of the student. The class should provide the following methods:
(1) void setName(String s): sets the name of the student to s.
(2) String getName(): returns the name of the student.
(3) void setDOB(String s): sets the DOB of the student to s
(4) String getDOB(): returns the DOB of the student.
(5) void setUniversity(String s): sets the university name to s
(6) String getUniversity(): returns the University name.
(7) void setHeight(double d): sets the height of the student to d
(8) double getHeight(): returns the height of the student.
Include a main method in the Student class that tests all of the methods you have defined.

Lab08 -- Section 5 -- Counter Class

Problem 2 -- Page 331

Wednesday, September 15, 2010

The Outsourcing of Your Education


I looks like user bstancel over at elance.com has posted a job bid that looks mighty similar to our Homework 3: Zuckerville. In fact, it looks identical, as you can see from the screenshot. Click on the image to see the full resolution, or click here to see the original (you can only see the full posting if you are registered with elance).

Of course, if bstancel was a student in my class then I am sure this would qualify as a violation of our honor code which I would have to report and would lead to all kinds of paperwork and possible expulsion of the student. So, its probably just someone else who really wants to play this awesome game I designed for your homework. As such, I have already bid $50 to do the job, so don't try to under bid me because, you can't. I already have the answer.

Tuesday, September 14, 2010

Lab 7--Section 6 -- Right Triangle Mirror Image

Write a Java program that asks a user to enter an integer from 1 to 50. The program should display like the following figure.

If the user enters 3, the output would be


***
**
*
**
***
Hint:
use nested for-loops; the outside loop controls the number of lines to write and the inside loop controls the number of asterisks to display on a line.

Lab07 -- Section 5 -- Perfect Medians

Objective Your goal (i.e., the requirement for this program) is to find all of the numbers between 1 and 10,000 that have a perfect median. A number n has a perfect median m if the sum of all the integers less than m is equal to the sum of all the integers greater than m, up to and including n. For example, the number n = 8 has the perfect median m = 6, because the sum of the integers from 1 to 5 is equal to the sum of the integers from 7 to 8.

Program Specification The key to your Java program Median.java is to test each integer to see if it is the perfect median for some sequence of integers. To test an integer m, add all of the integers from 1 to m-1. Then from this sum begin subtracting the integers greater than m. If the result becomes 0, then the last integer you subtracted is the number n that has a perfect median of m. If the result becomes negative, then m is not a perfect median for any number n, so try the next number. You might make use of the formula 1+2+...+(m-1) = m(m-1)/2

HW 3: Zuckerville

For your second homework you will implement the text-only farming game Zuckerville: a game for suckers digital farmers! Each player in this game has a plot of land that where he can plant some seeds. After 10 time steps these seeds will have grown into pretty flowers, at which point the player can plant more seeds, if he can afford them.

farmville

Below is a sample interaction of the player with the game.

Welcome to Zuckerville, where the only way to win is not to play!
We gave you $5 zuckerdollars to get you started! Now go plant!

[0 $5] Command: plant
[1 $5] Command: buy 5
You bought 5 seeds.
[2 $0] Command: plant
Planted a seed.
Planted a seed.
Planted a seed.
Planted a seed.
Planted a seed.
[3 $0] Command: plant
Sorry, there are already seeds planted there. You must wait till after harvest.
[4 $0] Command: fertilize
Sorry, it costs $4 to buy fertilizer.
[5 $0] Command: wait
What did you say?
[6 $0] Command: kdkdk
What did you say?
[7 $0] Command: gossip
What did you say?
[8 $0] Command: chat
What did you say?
[9 $0] Command: help
What did you say?
[10 $0] Command: oh
What did you say?
[11 $0] Command: I
What did you say?
You harvested a beautiful flower.
You harvested a beautiful flower.
You harvested a beautiful flower.
You harvested a beautiful flower.
You harvested a beautiful flower.
[12 $0] Command: plant
[13 $0] Command: buy 10
Sorry, you don't have enough zuckerdollars.
[14 $0] Command: deposit $10
You now have $10
[15 $10] Command: buy 10
You bought 10 seeds.
[16 $0] Command: plant
Planted a seed.
Planted a seed.
Planted a seed.
Planted a seed.
Planted a seed.
Planted a seed.
Planted a seed.
Planted a seed.
Planted a seed.
Planted a seed.
[17 $0] Command: fertilize
Sorry, it costs $4 to buy fertilizer.
[18 $0] Command: deposit $4
You now have $4
[19 $4] Command: fertilize
You fertilized your plot!
[20 $0] Command: wait
What did you say?
[21 $0] Command: w
What did you say?
[22 $0] Command: a
What did you say?
You harvested a beautiful flower.
You harvested a beautiful flower.
You harvested a beautiful flower.
You harvested a beautiful flower.
You harvested a beautiful flower.
You harvested a beautiful flower.
You harvested a beautiful flower.
You harvested a beautiful flower.
You harvested a beautiful flower.
You harvested a beautiful flower.
[23 $0] Command: quit
Goodbye!

As you can see, the game always gives the user a prompt (like [23 $0] Command:) where the first number (23) is the time and the second ($0) is the money (zuckerdollars) the user has in the game. The user has a few commands he can use:

  1. plant: the user plants all the seeds he has in his plot, but only if the plot is empty. If he has no seeds then nothing happens. If planting succeeds then the plot is now full; no more plantings are allowed until after the plants are harvested.
  2. fertilize: Normally seeds turn into flowers after 10 time steps but if they are fertilized then they grow twice as fast. Fertilizing costs $4.
  3. deposit $x, where x is the number of dollars the sucker player wants to paypal over to us. This code increases the player's zuckerdollars by x.
  4. buy x: the user buys x seeds, each seed costs 1 zuckerdollar. Make sure he has enough money to pay!
  5. quit: the game ends and the program exits.

The user sees a message for every seed he plants and every flower he harvests, as shown in the interaction above.

This program is due Tuesday, 21 September @9am in our dropbox.

HW 2 Solution

Here is my solution to HW 2.


import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;


public class Dice extends JPanel{

 /** The number the dice is showing. 0 for nothing */
 public int number;

 /** The radius of the dots in the dice. */
 public static final int RADIUS = 10;

 /** Draw the dice. 
  *  50,50       */
 public void paintComponent(Graphics g) {
  int height = getHeight();
  g.setColor(Color.black);
  g.drawRect(50, 50, 200, 200); //A 200x200 square offset by 50,50.
  switch (number) {
  case 0:
   break;
  case 5: //compiler will optimize these
   g.drawOval(100-RADIUS, 100-RADIUS, RADIUS*2, RADIUS*2); //top left
   g.drawOval(200-RADIUS, 200-RADIUS, RADIUS*2, RADIUS*2); //bottom right
  case 3:
   g.drawOval(200-RADIUS, 100-RADIUS, RADIUS*2, RADIUS*2); //top right
   g.drawOval(100-RADIUS, 200-RADIUS, RADIUS*2, RADIUS*2); //bottom left
  case 1:
   g.drawOval(150-RADIUS, 150-RADIUS, RADIUS*2, RADIUS*2); //center
   break;
  case 6:
   g.drawOval(100-RADIUS, 150-RADIUS, RADIUS*2, RADIUS*2); //center left
   g.drawOval(200-RADIUS, 150-RADIUS, RADIUS*2, RADIUS*2); //center right
  case 4:
   g.drawOval(100-RADIUS, 100-RADIUS, RADIUS*2, RADIUS*2); //top left
   g.drawOval(200-RADIUS, 200-RADIUS, RADIUS*2, RADIUS*2); //bottom right
  case 2:
   g.drawOval(200-RADIUS, 100-RADIUS, RADIUS*2, RADIUS*2); //top right
   g.drawOval(100-RADIUS, 200-RADIUS, RADIUS*2, RADIUS*2); //bottom left
   break;
  }
 }


 /**
  * @param args are ignored
  */
 public static void main(String[] args) {
  JFrame frame = new JFrame("Roll Them Bones");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  Dice panel = new Dice();
  frame.add(panel);
  frame.setSize(300, 300); //create a window that is 300px horizontally by 200px vertically.
  frame.setVisible(true);
  do {
   try {
    panel.number = Integer.parseInt(JOptionPane.showInputDialog("Enter number for the dice, or 0 to quit:"));
    frame.repaint(); //don't forget to re-paint it!
   } catch (NumberFormatException e) { //if the user types in something other than an integer, or clicks "cancel"
    System.exit(0); 

   }
  }
  while (panel.number != 0);
  System.exit(0); //without this the program won't end, cse its a GUI program.
 }
}

Friday, September 10, 2010

Chapter 5 Video

Below is the screencast for the Chapter 5 lecture which is on classes and methods. Java is an object-oriented programming (OOP) language, as are C++, C#, Python, Ruby, and many other modern programming languages. OOPs all have classes, objects, and methods.

CSCE 145: Chapter 5 from Jose Vidal on Vimeo.

Below are the slides for this chapter, for your review:

You will need to have read Chapter 5 and have watched the screencast before class on Thursday, September 16

Thursday, September 9, 2010

Lab 6- section 6

Problem 5 - page 231

Lab06 - Section 5

Problem 13 -- Page 233
-- Use a loop for validating the user input
-- Read carefully the Hint given to approach the problem

Tuesday, September 7, 2010

Lab 5 -Section 6

Problem 9 - page 172

Lab05-Section 5

Problem 9 -- Page 172 ... use combination of if .. else and switch case

HW 2: Dice

In this homework you will start with the simple GUI program I provide below and change it so that it displays the side of the dice that the user asks. First, cut-and-paste the program below to a new class called Dice. Run the program and note that it pops up 2 windows: one with an over and the other one with a text box that asks you to enter a number. When you enter a number the horizontal diameter of the oval changes accordingly. Also note that this program is a simple extension of the graphics supplement sections from your textbook.
/** Jose M Vidal 
 * TA Please NOTE: If that's not me on the line above then I deserve 0 points on this homework.
 */

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Dice extends JPanel {
 
 /** The horizontal diameter of the oval we will draw. */
 public int diameter;
 
 public void paintComponent(Graphics g) {
  int height = getHeight();
  g.setColor(Color.black);
  g.drawOval(0, 0, diameter, height);
 }
 
 public static void main(String args[]) {
  JFrame frame = new JFrame("An Oval");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  Dice panel = new Dice();
  panel.diameter = 100; //set the diameter of the oval
  frame.add(panel);
  frame.setSize(300, 200); //create a window that is 300px horizontally by 200px vertically.
  frame.setVisible(true);
  
  String diameterPane =
   JOptionPane.showInputDialog("Enter new diameter for the oval:");
  panel.diameter = Integer.parseInt(diameterPane); //set the new diameter
  if (panel.diameter == 0) {
   System.exit(0);
  }
  frame.repaint(); //don't forget to re-paint it!
  

 }
}
The program is also here (Dice.java). You will be making many changes to it.
The program you will write will ask the user for the number to display and then display that number in the face of the dice, as shown by the screenshots below.


Note that

  1. your program will continue asking the user for a new number right after displaying the one he just typed,
  2. when the user enters 0 the program should exit.

This program is due Tuesday, September 14 at 9am. Please deposit it in our dropbox or email it to us.

HW 1 Solution

Here is my solution to the HW1 problem:
/** @author Jose M Vidal  
 * Rotate lowercase only strings by an arbitrary amount, without using if-then statements.
 * */

import java.util.Scanner;

public class Rot13 {

 /**
  * @param args are ignored
  */
 public static void main(String[] args) {
  Scanner keyboard = new Scanner(System.in);
  System.out.print("What offset do you want?");
  int offset = keyboard.nextInt();
  System.out.print("Enter word to translate:");
  String inputWord = keyboard.next();
//  for (char c : inputWord.toCharArray()) { //a classier way to do the same
  for (int i = 0; i < inputWord.length(); i++) {
   //Don't replace ('z' - 'a' + 1) with its value, the compiler will do that.
   char c = inputWord.charAt(i);
   System.out.print((char)('a' + (c - 'a' + offset) % ('z' - 'a' + 1)));
  }
 }
}

Saturday, September 4, 2010

Chapter 4 Video

Below is the screencast for the Chapter 4 lecture. It is on loops: while and for loops. Every single programming language has while and for loops, and they are always named 'while' and 'for', although the specific syntax of the for-loops can change a little bit between programming languages. You need to have read Chapter 4 and watched the screencast before class on Thursday, September 9.

CSCE 145: Chapter 4 from Jose Vidal on Vimeo.

Here are the slides from the textbook, for your reviewing needs:

Thursday, September 2, 2010

HW 1 Update

I have updated the homework 1 by giving you some code that implements the for-loop you will need to use. I thought that for-loops where covered on Chapter 4, but they are not covered until Chapter 4.