Andre Stevens
XtraOrdinayr Software Development

Apr
29

Taken from the text .NET Framework Application Development Foundation (MCTS Exam 70-536):

 

Value types are variables that contain their data directly instead of containing a reference to the data stored elsewhere in memory. Instances of value types are stored in an area of memory called the stack, where the runtime can create, read, update and remove them quickly with minimal overhead.”

 

whereas

 

Reference types store the address of their data (a.k.a – a pointer), on the stack. The actual data that the address refers to is stored in an area of memory called the heap. Because reference types represent the address of data rather than the data itself assigning on reference variable to another doesn’t copy the data, but instead creates a second copy of the reference which points to the same memory location on the heap.”

 

I tend to remember the difference between reference and value types in terms of the kind of objects they are. Value types tend to be things like primitives, such as int, float and double; where reference types are like classes (such as StringBuilder, or ArrayList, or StreamReader).

 

Additionally, When creating a copy of a value type, if you change the value of one of it’s member variables, it won’t change the value in the original. I demonstrate that with this code:


namespace ValVsRefTypeDemo

{

struct ShipCallNumber

{

public int callNumber;

public ShipCallNumber(int callNum)

{

callNumber = callNum;

}

public override string ToString()

{

return callNumber.ToString();

}

}

class Program

{

static void Main(string[] args)

{

ShipCallNumber enterprise = new ShipCallNumber(1701);

ShipCallNumber voyager = enterprise;

enterprise.callNumber += 1;

voyager.callNumber += 24;

Console.WriteLine("Using Value Type\n-----------------------\nEnterprise: {0}\nVoyager: {1}\n", enterprise, voyager);

}

}

}

which resulted in:

Using Value Type

———————–

Enterprise: 1702

Voyager: 1725

 

Press any key to continue . . .

I also know that when we make a copy of the reference type we make a copy of the pointer to the value. So if we change the value it changes the value of any instances of the reference type; as in:


namespace ValVsRefTypeDemo

{

struct ShipCallNumber

{

public int callNumber;

public ShipCallNumber(int callNum)

{

callNumber = callNum;

}

public override string ToString()

{

return callNumber.ToString();

}

}

class CallNumber

{

public int cNumber;

public CallNumber(int _cNumber)

{

cNumber = _cNumber;

}

public override string ToString()

{

return cNumber.ToString();

}

}

class Program

{

static void Main(string[] args)

{

ShipCallNumber enterprise = new ShipCallNumber(1701);

ShipCallNumber voyager = enterprise;

enterprise.callNumber += 1;

voyager.callNumber += 24;

Console.WriteLine("Using Value Type\n-----------------------\nEnterprise: {0}\nVoyager: {1}\n", enterprise, voyager);

//using reference types

CallNumber cNumEnterprise = new CallNumber(1701);

CallNumber cNumVoyager = cNumEnterprise;

cNumEnterprise.cNumber += 1;

cNumVoyager.cNumber += 24;

Console.WriteLine("\n\nUsing Reference Type\n----------------------\nEnterprise call number: {0}\nVoyager call number: {1}\n", cNumEnterprise, cNumVoyager);

}

}

}

Which results in:

Using Value Type

———————–

Enterprise: 1702

Voyager: 1725

 

 

 

Using Reference Type

———————-

Enterprise call number: 1726

Voyager call number: 1726

 

Press any key to continue . . .

Apr
27

The following lab was taken from the Microsoft .NET Framework Application Development Foundation Training Kit for the MCTS Exam 70-536.

Declaring and Using Value Types:

Goal: Create a simple structure with several public members

Using Visual Studio (I’m using VS 11 at the time that I worked on this project) create a new console application project. Create a new structure named Person (for this sample I chose to make it a little more interesting by naming it AcademyStudent, in keeping with my favorite Star Trek theme.)

struct AcademyStudent
{
public enum Rank
{
Cadet,
Ensign,
LtJuniorGrade,
Lieutenant,
LiuetenantCommander,
InvalidRank
}

string firstName;
string lastName;
string homePlanet;
Rank studentRank;

public override string ToString()
{
return studentRank + " " + lastName + ", " + firstName + "\nHome Planet: " + homePlanet;
}

public AcademyStudent(string _fName, string _lName, string _homePlanet, Rank _studentRank)
{
firstName = _fName;
lastName = _lName;
homePlanet = _homePlanet;
studentRank = _studentRank;
}
}

In my sample I’ve included an enum (which was also a part of the second part of the lab in the text) that holds the rank of the student, while in attendance at Starfleet Academy, as well as defining the requisite three public members (for this sample I chose to create firstName, lastName, and homePlanet along with the studentRank enum) and creating a constructor that initializes all member variables. The lab then calls for us to write code to create an instance of the structure and pass the instance to the Console.WriteLine() method, within the Main method.

static void Main(string[] args)
{
AcademyStudent student = new AcademyStudent("Geordi", "LaForge", "Mars Colony", AcademyStudent.Rank.LiuetenantCommander);
Console.WriteLine(student);
}

Resulting in the following output:

LiuetenantCommander LaForge, GeordiHome Planet: Mars ColonyPress any key to continue . . .

Of course to make the application more interactive I might have done something like:

//interactive version
string rankMenu = string.Format("{0}\n{1}\n{2}\n{3}\n{4}", "1 - Cadet", "2 - Ensign", "3 - LtJuniorGrade", "4 - Lieutenant", "5 - LieutenantCommander");
Console.WriteLine("Choose your rank:\n");
Console.WriteLine(rankMenu);

int sRank = int.Parse(Console.ReadLine());
AcademyStudent.Rank rank = GetRank(sRank);      //converts the number into a valid rank; returns InvalidRank if the user enters a value other than the ones listed.

if (rank == AcademyStudent.Rank.InvalidRank)
{
Console.WriteLine("The rank you entered is invalid");
}
else
{
Console.WriteLine("Please enter your first name:");
string firstName = Console.ReadLine();

Console.WriteLine("\nPlease enter your last name:");
string lastName = Console.ReadLine();

Console.WriteLine("\nPlease enter your home planet:");
string homePlanet = Console.ReadLine();

AcademyStudent student1 = new AcademyStudent(firstName, lastName, homePlanet, rank);
Console.WriteLine("\n" + student1);
}

Notice that I use the following code to convert the user’s rank selection into the appropriate rank, and send that back to the program for “processing”

private static AcademyStudent.Rank GetRank(int _sRank)
{
switch (_sRank)
{
case 1:
return AcademyStudent.Rank.Cadet;
//break;

case 2:
return AcademyStudent.Rank.Ensign;
//break;

case 3:
return AcademyStudent.Rank.LtJuniorGrade;
//break;

case 4:
return AcademyStudent.Rank.Lieutenant;

case 5:
return AcademyStudent.Rank.LiuetenantCommander;

default:
return AcademyStudent.Rank.InvalidRank;

}
}
Choose your rank:1 – Cadet2 – Ensign

3 – LtJuniorGrade

4 – Lieutenant

5 – LieutenantCommander

5

Please enter your first name:

Nyota

Please enter your last name:

Uhura

Please enter your home planet:

Luna Colony

LieutenantCommander Uhura, Nyota

Home Planet: Luna Colony

Press any key to continue . . .

But this will send back the text of the Rank member formatted as it appears in the enum object (see highlighted item above). To format it so it looks more “human readable”, I’d modify the struct to include the following code:

private static string GetRank(Rank _rank)
{
switch (_rank)
{
case Rank.Cadet:
return "Cadet";
//break;

case Rank.Ensign:
return "Ensign";
//break;

case Rank.LtJuniorGrade:
return "Lieutenant Junior Grade";
//break;

case Rank.Lieutenant:
return "Lieutenant";

case Rank.LiuetenantCommander:
return "Lieutenant Commander";

default:
return "Invalid Rank";

}
}</pre>

Which returns an actual string (and not the value in the enum object).

Finally when I run it I get:

Choose your rank: 1 – Cadet2 – Ensign

3 – LtJuniorGrade

4 – Lieutenant

5 – LieutenantCommander

5

Please enter your first name:

Nyota

 

Please enter your last name:

Uhura

 

Please enter your home planet:

Luna Colony

 

Lieutenant Commander Uhura, Nyota

Home Planet: Luna Colony

Press any key to continue . .

I even worked some error checking into the mix….

Choose your rank: 1 – Cadet

2 – Ensign

3 – LtJuniorGrade

4 – Lieutenant

5 – LieutenantCommander

33

The rank you entered is invalid

Press any key to continue . . .

NOTES:

I realize that the application could use some more error checking (like checking the entries for the name, and home planet). I will endeavor to prepare that solution in a later version.

Apr
26

The following was taken from the exercises found in Teach Yourself Java 6 in 21 Days. Chapter (Day) 3, p87:

Goal: Create a class with instance variables for height, weight and dept, making each an integer. Create a Java application that uses your new class, sets each of these values in an object, and displays the values.

The following is the code I used to create the class. Although the original code didn’t call for it, I followed the convention of setting the member variables to private and using properties (“getters” and “setters”) to make retrieving and modifying the variables more safe. I also put the functionality of displaying the values of the variables in a method called DisplayValues().

/**
*
* @author Andre Stevens
*/
public class Measurements {
private int height, weight, depth;
public void DisplayValues(){
System.out.println("Height: " + getHeight() + "\nWeight: " + getWeight() + "\nDepth: " + getDepth());
}
public Measurements(){
}
public Measurements(int ht, int wt, int dp){
height = ht;
weight = wt;
depth = dp;
}
/**
* @return the height
*/
public int getHeight() {
return height;
}
/**
* @param height the height to set
*/
public void setHeight(int height) {
this.height = height;
}
/**
* @return the weight
*/
public int getWeight() {
return weight;
}
/**
* @param weight the weight to set
*/
public void setWeight(int weight) {
this.weight = weight;
}
/**
* @return the depth
*/
public int getDepth() {
return depth;
}
/**
* @param depth the depth to set
*/
public void setDepth(int depth) {
this.depth = depth;
}
}

In the main method I instantiated the class by using:

package measurementsdemo;
/**
*
* @author Andre Stevens
*/
public class MeasurementsDemo {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Measurements measure = new Measurements(8, 9, 10);

System.out.println("The current measurements are:\n");
measure.DisplayValues();
}
}

Resulting in:

run: 

The current measurements are: 
Height: 8 
Weight: 9 
Depth: 10

 

I used the constructor for the Measurements class to pass in the values for the variables. However I could have written the code:

package measurementsdemo;
/**
*
* @author Andre Stevens
*/
public class MeasurementsDemo {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
 Measurements measure = new Measurements(8, 9, 10);
 System.out.println("The current measurements are:\n");
 measure.DisplayValues();

//passing in valuses using the properties:
Measurements measure2 = new Measurements();
measure2.setHeight(24);
measure2.setWeight(119);
measure2.setDepth(300);

System.out.println("\nThe updated measurements are:\n");
measure2.DisplayValues();
}
}

Resulting in:

run: 

The current measurements are: 

Height: 8 
Weight: 9 
Depth: 10  

The updated measurements are: 

Height: 24 
Weight: 119 
Depth: 300
Apr
26

This exercise was taken from the Teach Yourself Java 6 in 21 Days (5th edition) text. From Day 3, p 87:

Goal: Create a program that turns a birthday in MM/DD/YYYY format (such as 12/04/2007) into three individual strings:

My first pass at the solution I came up with:


package extractdatedemo;

import java.util.StringTokenizer;

/**
*
* @author Andre Stevens
*/
public class ExtractDateDemo {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
    String dateStr = "11/20/1968";
    StringTokenizer str = new StringTokenizer(dateStr, "/");

    //NOTE prints out one less than the actuall number of elements
    for(int cnt = 0; cnt < str.countTokens(); cnt++)
    {
       System.out.println(str.nextToken());
    }
  }
}

But I soon came to discover that the countTokens() method gives me only the month and day because it doesn’t advance the current position and calculates how many times it can call the nextToken() method before an exception is generated. Using the Intellisense in Netbeans, I investigated the StringTokenizer object to find it has a hasMoreToekns() method, which seemed to  provide just the functionality I would need; so I rewrote the code:


package extractdatedemo;

import java.util.StringTokenizer;

/**
*
* @author Andre Stevens
*/
public class ExtractDateDemo {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
    String dateStr = "11/20/1968";
    StringTokenizer str = new StringTokenizer(dateStr, "/");

    while(str.hasMoreTokens())
    {
        System.out.println(str.nextToken());
    }
  }
}

Resulting in:

run:

11

20

1968

BUILD SUCCESSFUL (total time: 1 second)

Which is exactly what I expected.

In this version of my solution I hard coded the date into the solution. In a future update of the code I will have the application prompt the user for the date.

Apr
25

Demonstration of coding basics in Java:

The following is one of the coding examples from the book Teach Yourself Java 6 in 21 Days. Here I’m demonstrating my solution to the exercise.

 

Goal: Create a program that calculates how much a $14, 000 investment would be worth if it increased in value by 40% during the first year, lost $1500 in value the second year, and increased 12% in the third year.

 

My first pass at the problem I use constants for the values given. But I also realize that this could be a more generic program and will make an attempt to make it more abstract in a second pass:

 

I create a variable to hold the original investment of $14,000; additionally, I decided to store the increase in a variable as well. I stored the total, remaining, and loss in additional variables, using doubles, since this was currency:

 


public static void main(String[] args) {
    double investment = 14000.00;
    double gain = .40;
    double remaining, total, loss;
.
.
.

 

Next I calculated the investment with the 40% gain:

 

//40% increase in first year
total = investment + (investment * gain);

System.out.println("FIRST YEAR REPORT: Your $" + investment +
" investment had a " + (gain * 100) +
"% increase." + "\nTotal is: $" + total)

 

I formatted the output with a header that showed the first year investment status. I used

(gain * 100)

 

to format the display of the variable double gain = .40;

 

I displayed the loss with:

 

//$1500 loss in the second year
loss = 1500.00;
remaining = total - loss;
System.out.println("\nSECOND YEAR REPORT: Your $" + total + " investment had a loss of $1500.00" +
"\nTotal is: $" + remaining);

 

using the loss and remaining variables to help calculate the investment after the loss.

 

Finally I use the following code to calculate the 12% increase in the third year:

 

//12% increase in the third year
gain = .12;
total = remaining + (remaining * gain);
System.out.println("\nTHIRD YEAR REPORT: Your $" + remaining +
" investment had a " + (gain * 100) +
"% increase." + "\nTotal is: $" + total);

 

My second pass at the problem would prompt the user for the values and whether it was a loss or gain and then calculated the totals accordingly.

Of course current financial programs are much more sophisticated, being able to determine whether there was a loss or gain, but for the purposes of this example we’re keeping it simple.

Mar
26

Let me start out by saying that the application I’m demonstrating here is just that: a demonstration. It is not affiliated with Star Trek or Paramount Pictures in any way. I simply wanted to demonstrate how to build an app using OOP and it’s constructs, and I thought a complex application like a “university” registration system would provide a good jumping off point (and since I’m a huge Star Trek fan, I thought using a Star Trek  theme might be fun as well!)

That said, It’s time to “…boldly go…” well you know the rest….

I decided to start by fleshing out the specs of what I wanted to accomplish. The following is the result of my thought processes:

Goal:To create a Starfleet Academy application that will

  1. Display a list of all students (NOTE:administrator priv only?)
  2. Display a list of students given specific criterion (NOTE:i.e. – freshmen, juniors, graduation dates, etc)
  3. Display a list of available courses for enrollment
    1. courses should list days and times
    2. courses should list the instructor
    3. courses should have
      • id
      • name
      • description
  4. Allow Academy students to
    1. look up grades
    2. enroll in courses (NOTE: a student cannot re-enroll in a course they’ve already taken and passed; a student cannot advance in a study track without passing required courses)
    3. drop courses (a student cannot drop a course after 3 weeks unless there is a valid reason to do so – i.e. – death in the family)
    4. request new living quarters
  5. Allow instructors to grade their students
  6. Calculate student GPAs

In a future release, I will create an admin app that will: (NOTE:must have a login account)

  1. Allow the addition or expulsion of students (NOTE:must include a reason)
  2. Allow the addition or removal of instructors (NOTE:must include a reason)
  3. The creation or deletion of courses
  4. Assign living quarters to students

 

In addition to the specs, I outlined some of the classes that I’d likely be using:

Objects:abstract class Starfleet Academymethod: RegisterStudent()Properties:RankStatusFirst NameLast Name

Home Planet

Date of Birth

Methods:

DisplayStudents(); (NOTE: displays all students)

DisplayStudentsByYear(); (NOTE: displays students by academic year (i.e. – freshman, junior, etc)

DisplayCourses();

RegisterForClass();

ChangeResidence();

DropStudent()

PromoteStudent(); (NOTE: can only be promoted from Cadet Fourth Class – Cadet First Class)

DemoteStudent()

property: ClassYear (freshman, sophomore, etc)

class Students : StarfleetAcademy (will inherit some of the properties of StarfleetAcademy)

Properties:

Grade Point Average (GPA) (NOTE: I represented the GPA rather than the grade for the student, because it represents his/her overall cumulative standing while at the academy)

List<Class> Semester = new List<Class>() (NOTE: list of the classes the student is taking for any given semester)

Methods:

class Instructors : StarfleetAcademy (will inherit some of the properties of StarfleetAcademy)

Properties:

Method:

class AcademyClass

Properties:

public int Course ID { get; set; }

public string Course Name { get; set; }

public string Instructor { get; set; }

public string Description { get; set; }

List<string> Prerequisites

public int Student Grade { get; set; }

(NOTE: the grade is a part of class because it represents the student’s standing in the class)

Methods:

MakeActive()

MakeInactive()

Tests (questions, answers)

I also created a Starfleet Academy class library which will house much of the general functionality that might be found in a registration application:

AcademyPersonnel Super Class

Click image to make larger...

In this release of the application, I’ve chosen to create a super class AcademyPersonnel which will provide the properties and methods to the Academy faculty and students. The super class also provide ID’s for the instructors and students using a static field PersonnelID, which is incremented in each new instance of the AcademyInstructor and AcademyStudent. In a future release this will be handled by the database.

Now to derive new objects from the classes in the library….

Mar
06

I’ve discovered a great little site that not only helps me hone my problem solving skills, but offers a great way fro me to review my basic Java skills, as well. CodingBat Code Practice has offered me quite a few little “warm ups” that have been keeping me buys most nights, and helping me refine my ability to come up with solutions, by helping me take a step back and follow the “K.I.S.S.” rule. The site is interactive enough to let you know when you’ve made errors, and when you’ve “done good”. I’ll post some of the problems and my solutions….

Sleep In:

Description: The parameter weekday is true if it is a weekday, and the parameter vacation is true if we are on vacation. We sleep in if it is not a weekday or we’re on vacation. Return true if we sleep in. 

sleepIn(false, false) → true
sleepIn(true, false) → false
sleepIn(false, true) → true


public boolean sleepIn(boolean weekday, boolean vacation) {
}

This is probably one of the more simple problems in that the algorithm is practically written in the spec. 

Pseudo Code:

“if weekday and not on vacation

return false;

otherwise if not a weekday or on vacation

return true;”

My Solution:
public boolean sleepIn(boolean weekday, boolean vacation) {
if(weekday && !vacation)
return false;
else
return true;

}

Dec
23

Create a class that takes words for the first 10 numbers (ex: “one” , “two”, “three”…”ten”)and converts them into a single long integer. Use a switch statement for the conversion.

My solution was to create a string array to hold the number words, and an in array to hold the converted numbers. Then I looped through the int array and printed each number on the same line (rather than a new line for each number).

(NOTE: all of my solutions are created using NetBeans 7.0 IDE)

REM: tester class:


public class NumWordsDemo {

/**
 * @param args the command line arguments
 */
 public static void main(String[] args) {
 String[] numberWords = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};
 NumWords nw = new NumWords();
 nw.ConvertWords(numberWords);
 }
}

REM: class where number conversion takes place


public class NumWords {

//stores the converted numbers
 int[] numbers = new int[10];

 public void ConvertWords(String[] numWords){
 for(int index = 0; index < numWords.length; index++){

 //use the index to represent the numbers in the string array
 switch(index){
 case 0:
 case 1:
 case 2:
 case 3:
 case 4:
 case 5:
 case 6:
 case 7:
 case 8:
 case 9:
 numbers[index] = index + 1; //since it's zero based we need to add one to the number
 break;
 }
 }

 //display "single long integer" by looping through the int array
 for(int x = 0; x < numbers.length; x++)
 System.out.print(numbers[x]);
 System.out.println("\n");
 }
}

Dec
23

Greetings!

…and thank you for visiting my blog. My goal here is to use this blog as a forum where I will post sample projects [that come up in my texts] and my subsequent solutions, along with comments in the code, which will, hopefully, explain my reasoning for choosing a particular solution.

It is my hope to get feedback from my more senior peers, in the development arena, to help me hone my skills, so that I can better assist small businesses with their web development projects.

I look forward to some interesting (and challenging) discussions….

Big Dre—


Follow

Get every new post delivered to your Inbox.