Java: Lists

ListADT.java



import java.util.Iterator;

/**
 * ListADT defines the interface to a general list collection. Specific
 * types of lists will extend this interface to complete the
 * set of necessary operations.
 *
 * @author Java Foundations
 * @version 4.0
 */
public interface ListADT<T> extends Iterable<T>
{
    /**
     * Removes and returns the first element from this list.
     *
     * @return the first element from this list
     */
    public T removeFirst();

    /**
     * Removes and returns the last element from this list.
     *
     * @return the last element from this list
     */
    public T removeLast();

    /**
     * Removes and returns the specified element from this list.
     *
     * @param element the element to be removed from the list
     */
    public T remove(T element);

    /**
     * Returns a reference to the first element in this list.
     *
     * @return a reference to the first element in this list
     */
    public T first();

    /**
     * Returns a reference to the last element in this list.
     *
     * @return a reference to the last element in this list
     */
    public T last();

    /**
     * Returns true if this list contains the specified target element.
     *
     * @param target the target that is being sought in the list
     * @return true if the list contains this element
     */
    public boolean contains(T target);

    /**
     * Returns true if this list contains no elements.
     *
     * @return true if this list contains no elements
     */
    public boolean isEmpty();

    /**
     * Returns the number of elements in this list.
     *
     * @return the integer representation of number of elements in this list
     */
    public int size();

    /**
     * Returns an iterator for the elements in this list.
     *
     * @return an iterator over the elements in this list
     */
    public Iterator<T> iterator();

    /**
     * Returns a string representation of this list.
     *
     * @return a string representation of this list
     */
    public String toString();
}

LinkedList.java


import java.util.*;

/**
 * LinkedList represents a linked implementation of a list.
 *
 * @author Java Foundations
 * @version 4.0
 */
public abstract class LinkedList<T> implements ListADT<T>, Iterable<T>
{
    protected int count;
    protected LinearNode<T> head, tail;
	protected int modCount;

    /**
     * Creates an empty list.
     */
    public LinkedList()
    {
        count = 0;
        head = tail = null;
		modCount = 0;
	}

    /**
     * Removes the first element in this list and returns a reference
     * to it. Throws an EmptyCollectionException if the list is empty.
     *
     * @return a reference to the first element of this list
     * @throws EmptyCollectionException if the list is empty
     */
    public T removeFirst() throws EmptyCollectionException
    {
       if (isEmpty())
            throw new EmptyCollectionException("LinkedList");

        LinearNode<T> previous = null;
        LinearNode<T> current = head;

        if (size() == 1)  // only one element in the list
            head = tail = null;
        else// target is at the head
            head = current.getNext();

        count--;
		modCount++;

        return current.getElement();
    }

    /**
     * Removes the last element in this list and returns a reference
     * to it. Throws an EmptyCollectionException if the list is empty.
     *
     * @return the last element in this list
     * @throws EmptyCollectionException if the list is empty
     */
    public T removeLast() throws EmptyCollectionException
    {
        if (isEmpty())
            throw new EmptyCollectionException("LinkedList");

        LinearNode<T> previous = null;
        LinearNode<T> Prevprevious = null; // the last last
        LinearNode<T> current = head;

		while (current != null)
        {
        	Prevprevious = previous;
        	previous = current;	
        	current = current.getNext();
        }
        
        if (size() == 1)  // only one element in the list
            head = tail = null;
        else{
	       // target is at the tail
	        tail = Prevprevious;
	        tail.setNext(null);
        }

        count--;
        modCount++;
		
		return previous.getElement();
    }

    /**
     * Removes the first instance of the specified element from this
     * list and returns a reference to it. Throws an EmptyCollectionException
     * if the list is empty. Throws a ElementNotFoundException if the
     * specified element is not found in the list.
     *
     * @param  targetElement the element to be removed from the list
     * @return a reference to the removed element
     * @throws EmptyCollectionException if the list is empty
	 * @throws ElementNotFoundException if the target element is not found
     */
    public T remove(T targetElement) throws EmptyCollectionException,
         ElementNotFoundException
    {
        if (isEmpty())
            throw new EmptyCollectionException("LinkedList");

        boolean found = false;
        LinearNode<T> previous = null;
        LinearNode<T> current = head;

        while (current != null && !found)
            if (targetElement.equals(current.getElement()))
                found = true;
            else
            {
                previous = current;
                current = current.getNext();
            }

        if (!found)
            throw new ElementNotFoundException("LinkedList");

        if (size() == 1)  // only one element in the list
            head = tail = null;
        else if (current.equals(head))  // target is at the head
            head = current.getNext();
        else if (current.equals(tail))  // target is at the tail
        {
            tail = previous;
            tail.setNext(null);
        }
        else  // target is in the middle
            previous.setNext(current.getNext());

        count--;
		modCount++;

        return current.getElement();
    }

    /**
     * Returns the first element in this list without removing it.
     *
     * @return the first element in this list
	 * @throws EmptyCollectionException if the list is empty
     */
    public T first() throws EmptyCollectionException
    {
        if (isEmpty())
            throw new EmptyCollectionException("LinkedList");

        return head.getElement();
    }

    /**
     * Returns the last element in this list without removing it.
     *
     * @return the last element in this list
	 * @throws EmptyCollectionException if the list is empty
     */
    public T last() throws EmptyCollectionException
    {
        if (isEmpty())
            throw new EmptyCollectionException("LinkedList");

        return tail.getElement();
    }

    /**
     * Returns true if the specified element is found in this list and
     * false otherwise. Throws an EmptyCollectionException if the list
	 * is empty.
     *
     * @param  targetElement the element that is sought in the list
     * @return true if the element is found in this list
     * @throws EmptyCollectionException if the list is empty
     */
    public boolean contains(T targetElement) throws
         EmptyCollectionException
    {
         if (isEmpty())
            throw new EmptyCollectionException("LinkedList");

        LinearNode<T> previous = null;
        LinearNode<T> current = head;

        while (current != null)
            if (targetElement.equals(current.getElement()))
                return true;
            else
            {
                previous = current;
                current = current.getNext();
            }

       return false;
    }

    /**
     * Returns true if this list is empty and false otherwise.
     *
     * @return true if the list is empty, false otherwise
     */
    public boolean isEmpty()
    {
        return count == 0;
    }

    /**
     * Returns the number of elements in this list.
     *
     * @return the number of elements in the list
     */
    public int size()
    {
        return count;
    }

    /**
     * Returns a string representation of this list.
     *
     * @return a string representation of the list
     */
    public String toString()
    {
        if (isEmpty())
       	 throw new EmptyCollectionException("LinkedList");

		String output = "";
		
        LinearNode<T> tempHead = head;

        while(tempHead != null)
        {
            output += tempHead.getElement() + ", ";
            tempHead = tempHead.getNext();
        }


        return output;
    }




    /**
     * Returns an iterator for the elements in this list.
     *
     * @return an iterator over the elements of the list
     */
    public Iterator<T> iterator()
    {
        return new LinkedListIterator();
    }

	/**
	 * LinkedIterator represents an iterator for a linked list of linear nodes.
	 */
	private class LinkedListIterator implements Iterator<T>
	{
		private int iteratorModCount;  // the number of elements in the collection
		private LinearNode<T> current;  // the current position

		/**
		 * Sets up this iterator using the specified items.
		 *
		 * @param collection  the collection the iterator will move over
		 * @param size        the integer size of the collection
		 */
		public LinkedListIterator()
		{
			current = head;
			iteratorModCount = modCount;
		}

		/**
		 * Returns true if this iterator has at least one more element
		 * to deliver in the iteration.
		 *
		 * @return  true if this iterator has at least one more element to deliver
		 *          in the iteration
		 * @throws  ConcurrentModificationException if the collection has changed
		 *          while the iterator is in use
		 */
		public boolean hasNext() throws ConcurrentModificationException
		{
			if (iteratorModCount != modCount)
				throw new ConcurrentModificationException();

			return (current != null);
		}

		/**
		 * Returns the next element in the iteration. If there are no
		 * more elements in this iteration, a NoSuchElementException is
		 * thrown.
		 *
		 * @return the next element in the iteration
		 * @throws NoSuchElementException if the iterator is empty
		 */
		public T next() throws ConcurrentModificationException
		{
			if (!hasNext())
				throw new NoSuchElementException();

			T result = current.getElement();
			current = current.getNext();
			return result;
		}

		/**
		 * The remove operation is not supported.
		 *
		 * @throws UnsupportedOperationException if the remove operation is called
		 */
		public void remove() throws UnsupportedOperationException
		{
			throw new UnsupportedOperationException();
		}
	}

}

ArrayList.java


import java.util.*;

/**
 * ArrayList represents an array implementation of a list. The front of
 * the list is kept at array index 0. This class will be extended
 * to create a specific kind of list.
 *
 * @author Java Foundations
 * @version 4.0
 */
public abstract class ArrayList<T> implements ListADT<T>, Iterable<T>
{
    private final static int DEFAULT_CAPACITY = 100;
    private final static int NOT_FOUND = -1;

    protected int rear;
    protected T[] list;
	protected int modCount;

    /**
     * Creates an empty list using the default capacity.
     */
    public ArrayList()
    {
        this(DEFAULT_CAPACITY);
    }

    /**
     * Creates an empty list using the specified capacity.
     *
     * @param initialCapacity the integer value of the size of the array list
     */
    public ArrayList(int initialCapacity)
    {
        rear = 0;
        list = (T[])(new Object[initialCapacity]);
		modCount = 0;
    }

    /**
     * Creates a new array to store the contents of this list with
     * twice the capacity of the old one. Called by descendant classes
	 * that add elements to the list.
     */
    protected void expandCapacity()
    {
        // To be completed as a Programming Project
    }

    /**
     * Removes and returns the last element in this list.
     *
     * @return the last element in the list
     * @throws EmptyCollectionException if the element is not in the list
     */
    public T removeLast() throws EmptyCollectionException
    {
        // To be completed as a Programming Project
    }

    /**
     * Removes and returns the first element in this list.
     *
     * @return the first element in the list
     * @throws EmptyCollectionException if the element is not in the list
     */
    public T removeFirst() throws EmptyCollectionException
    {
        // To be completed as a Programming Project
    }

    /**
     * Removes and returns the specified element.
     *
     * @param  element the element to be removed and returned from the list
     * @return the removed elememt
     * @throws ElementNotFoundException if the element is not in the list
     */
    public T remove(T element)
    {
        T result;
        int index = find(element);

        if (index == NOT_FOUND)
            throw new ElementNotFoundException("ArrayList");

        result = list[index];
        rear--;

        // shift the appropriate elements
        for (int scan=index; scan < rear; scan++)
            list[scan] = list[scan+1];

        list[rear] = null;
		modCount++;

        return result;
    }

    /**
     * Returns a reference to the element at the front of this list.
     * The element is not removed from the list.  Throws an
     * EmptyCollectionException if the list is empty.
     *
     * @return a reference to the first element in the list
     * @throws EmptyCollectionException if the list is empty
     */
    public T first() throws EmptyCollectionException
    {
        // To be completed as a Programming Project
    }

    /**
     * Returns a reference to the element at the rear of this list.
     * The element is not removed from the list. Throws an
     * EmptyCollectionException if the list is empty.
     *
     * @return a reference to the last element of this list
     * @throws EmptyCollectionException if the list is empty
     */
    public T last() throws EmptyCollectionException
    {
        // To be completed as a Programming Project
    }

    /**
     * Returns true if this list contains the specified element.
     *
     * @param target the target element
     * @return true if the target is in the list, false otherwise
     */
    public boolean contains(T target)
    {
        return (find(target) != NOT_FOUND);
    }

    /**
     * Returns the array index of the specified element, or the
     * constant NOT_FOUND if it is not found.
     *
     * @param target the target element
     * @return the index of the target element, or the
     *         NOT_FOUND constant
     */
    private int find(T target)
    {
        int scan = 0;
		int result = NOT_FOUND;

        if (!isEmpty())
            while (result == NOT_FOUND && scan < rear)
                if (target.equals(list[scan]))
                    result = scan;
                else
                    scan++;

        return result;
    }

    /**
     * Returns true if this list is empty and false otherwise.
     *
     * @return true if the list is empty, false otherwise
     */
    public boolean isEmpty()
    {
        // To be completed as a Programming Project
    }

    /**
     * Returns the number of elements currently in this list.
     *
     * @return the number of elements in the list
     */
    public int size()
    {
        // To be completed as a Programming Project
    }

    /**
     * Returns a string representation of this list.
     *
     * @return the string representation of the list
     */
    public String toString()
    {
        // To be completed as a Programming Project
    }

    /**
     * Returns an iterator for the elements currently in this list.
     *
     * @return an iterator for the elements in the list
     */
    public Iterator<T> iterator()
    {
        return new ArrayListIterator();
    }

	/**
	 * ArrayListIterator iterator over the elements of an ArrayList.
	 */
	private class ArrayListIterator implements Iterator<T>
	{
		int iteratorModCount;
		int current;

		/**
		 * Sets up this iterator using the specified modCount.
		 *
		 * @param modCount the current modification count for the ArrayList
		 */
		public ArrayListIterator()
		{
			iteratorModCount = modCount;
			current = 0;
		}

		/**
		 * Returns true if this iterator has at least one more element
		 * to deliver in the iteration.
		 *
		 * @return  true if this iterator has at least one more element to deliver
		 *          in the iteration
		 * @throws  ConcurrentModificationException if the collection has changed
		 *          while the iterator is in use
		 */
		public boolean hasNext() throws ConcurrentModificationException
		{
			if (iteratorModCount != modCount)
				throw new ConcurrentModificationException();

			return (current < rear);
		}

		/**
		 * Returns the next element in the iteration. If there are no
		 * more elements in this iteration, a NoSuchElementException is
		 * thrown.
		 *
		 * @return  the next element in the iteration
		 * @throws  NoSuchElementException if an element not found exception occurs
		 * @throws  ConcurrentModificationException if the collection has changed
		 */
		public T next() throws ConcurrentModificationException
		{
			if (!hasNext())
				throw new NoSuchElementException();

			current++;

			return list[current - 1];
		}

		/**
		 * The remove operation is not supported in this collection.
		 *
		 * @throws UnsupportedOperationException if the remove method is called
		 */
		public void remove() throws UnsupportedOperationException
		{
			throw new UnsupportedOperationException();
		}

	}
}

C#: File handling: Reading, Example using Student Average

MainForm.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

/****    
*
* Name: Michael Peng
* Student Number: T00055798
* Seminar Number: 5
* Due Date: March 3, 2015
*
* Program Purpose:  Allows user to either select a student or a day, and displays the average
*                   based on user choice, or show all the students and day and display the averages.
*
****/

namespace Student_Average
{
    public partial class Form1 : Form
    {
        String[] Student;
        StreamReader inputFile;
        double[] studentAverage;
        double[] dayAverage;
        int[,] spendings;
        int rows, cols;

        public Form1()
        {
            InitializeComponent();

            inputFile = File.OpenText("E:/c#/studentSample.txt");
            String[] stringIndex = inputFile.ReadLine().Split(null);

            rows = int.Parse(stringIndex[0]);
            cols = int.Parse(stringIndex[1]);

            Student = new String[rows];
            spendings = new int[rows, cols];

            studentAverage = new double[rows];
            dayAverage = new double[cols];
        }

        private void Form1_Load(object sender, EventArgs e)
        {        
            populateData();

            displayStudents();

            displayDays();

            calculateAverage();
        }
        public void populateData()
        {  
            Student = new String[rows];//holds student names

            for (int names = 0; names < rows; names++) //populates student names in list box
            {
                Student[names] = inputFile.ReadLine();
            }

            spendings = new int[rows, cols];//holds the new grades

            for (int row = 0; row < rows; row++)
            {
                String[] expenditureString = inputFile.ReadLine().Split(null); //holds string spendings

                for(int col = 0; col < cols; col++)
                {
                    spendings[row, col] = int.Parse(expenditureString[col]); //holds int spendings
                }           
            }
            inputFile.Close();

        }

        public void displayStudents()
        {
            for (int names = 0; names < Student.Length; names++) //populates student names in list box
                studentListBox.Items.Add(Student[names]);
        }

        public void displayDays()
        {
            for (int day = 1; day <= cols; day++) // populates day numbers in list box
                dayListBox.Items.Add(day);
        }

        public void calculateAverage()
        {
            
            for(int row = 0; row < spendings.GetLength(0); row++)
            {
                for (int col = 0; col < spendings.GetLength(1); col++)
                {
                    studentAverage[row] += spendings[row, col];
                    dayAverage[col] += spendings[row, col];
                }               
            }

            for (int row = 0; row < spendings.GetLength(0); row++)//Averages student expense
                studentAverage[row] = studentAverage[row] / spendings.GetLength(1);

            for (int col = 0; col < spendings.GetLength(1); col++)//Averages daily expense
                dayAverage[col] = dayAverage[col] / spendings.GetLength(0);
        }

        private void showAllButton_Click(object sender, EventArgs e)
        {
            outputClear();

            outputListBox.Items.Add("Student\t Daily Spendings");
            outputListBox.Items.Add("Name\t\t" + stringDays(cols) + "Average per person");

            for (int row = 0; row < spendings.GetLength(0); row++)
            {
                String data ="";
                data += Student[row] + "\t";

                for (int col = 0; col < spendings.GetLength(1); col++)
                    data += spendings[row, col] + "\t";

                data += studentAverage[row].ToString("f");
                outputListBox.Items.Add(data);
            }

            String moreData = "Average per day\t";

            for (int day = 0; day < dayAverage.Length; day++)
                moreData += dayAverage[day].ToString("f") + "\t";

            outputListBox.Items.Add(moreData);
        }

        public String stringDays(int days)
        {
            String day ="";
            for (int i = 1; i <= days; i++) // populates day numbers in list box
                day += "Day " + i.ToString() +"\t";

            return day;
        }
        

        private void showStudentButton_Click(object sender, EventArgs e)
        {
            outputClear();
            String data ="";

            if(studentListBox.SelectedIndex == -1)
                MessageBox.Show("Please select a student first");
            else
            {
                outputListBox.Items.Add(studentListBox.SelectedItem+ " spendings");
                outputListBox.Items.Add(stringDays(cols) + "Average");


                for (int col = 0; col < spendings.GetLength(1); col++)
                    data += spendings[studentListBox.SelectedIndex, col] + "\t";

                data += studentAverage[studentListBox.SelectedIndex].ToString("f");

                outputListBox.Items.Add(data);
                
            }

        }

        private void showDayButton_Click(object sender, EventArgs e)
        {
            outputClear();

            if (dayListBox.SelectedIndex == -1)
                MessageBox.Show("Please select a day first");
            else
            {
                outputListBox.Items.Add("Student's Day " + dayListBox.SelectedItem + " spendings");
                outputListBox.Items.Add("Name");

                for (int row = 0; row < spendings.GetLength(0); row++)
                {
                    String data = "";
                    data += Student[row] + "\t";

                    data += spendings[row, dayListBox.SelectedIndex] + "\t";

                    outputListBox.Items.Add(data);
                }

                outputListBox.Items.Add("Average \t\t"+dayAverage[dayListBox.SelectedIndex].ToString("f"));

            }

        }

        public void outputClear()
        {
            outputListBox.Items.Clear();
        }

        private void clearButton_Click(object sender, EventArgs e)
        {
            outputClear();
        }

        private void exitButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}

Reading Daily spending for a single student
showday

Reading students spending for a day
output1sem5

Show all
showall

The text file the program is reading from:
output2sem5

C#: File Handling: Reading and Writing, Example using vacations

vacationAdd.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/****    
*
* Name: Michael Peng
* Student Number: T00055798
* Seminar Number: 7
* Due Date: March 24, 2015
*
* Class Purpose:  Hold private backing field data about a vacation,
*                 as well as gets and sets methods for all of them
*
****/
namespace Vacation
{
    public class vacationAdd
    {
        //backing fields have an _before them
        private int _length;
        private double _cost;
        private string _location;

        public vacationAdd()
        {
            _length = 0;
            _cost = 0.0;
            _location = "";
        }
        public int Length
        {
            get { return _length; }
            set { _length = value; } 
        }
        public double Cost
        {
            get { return _cost; }
            set { _cost = value; }
        }
        public string Location
        {
            get { return _location; }
            set { _location = value; }
        }
    }
}

vacationForm.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
/****    
*
* Name: Michael Peng
* Student Number: T00055798
* Seminar Number: 6
* Due Date: March 10, 2015
*
* Program Purpose:  Allows user to add more vacations, details about the destination, the 
*                   length of stay and cost. Also allows user to add up to 10 more vacations.
*
****/
namespace Vacation
{
    public partial class vacationForm : Form
    {
        MainForm form;

        public vacationForm(MainForm frm)
        {
            InitializeComponent();
            form = frm;
        }

        private void addButton_Click(object sender, EventArgs e)
        {
            getNewData();
        }
        public void getNewData()
        {
            try
            {             
                string newDestination = destinationTextBox.Text;
                int newDay = int.Parse(dayTextBox.Text);
                double newCost = double.Parse(costTextBox.Text);

                addData(newDestination, newDay, newCost);

                writeToFile(newDestination, newDay, newCost);

                MessageBox.Show("Vacation was successfully added!");

                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public void addData(string destination, int day, double cost)
        {
            vacationAdd addVac = new vacationAdd();

            addVac.Location = destination;
            addVac.Length = day;
            addVac.Cost = cost;

            form.addDestination(addVac);
            
        }
        public void writeToFile(string destination, int day, double cost)
        {
            StreamWriter outputFile = File.AppendText("vacations.txt");

            outputFile.WriteLine(destination + "," + day + "," + cost);

            outputFile.Close();
        }
    }
}

MainForm.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
/****    
*
* Name: Michael Peng
* Student Number: T00055798
* Seminar Number: 7
* Due Date: March 24, 2015
*
* Program Purpose:  Allows user to learn more information about a vacation destination, regarding the 
*                   length of stay and cost. Also allows user to click a button to add a vacation.
*
****/

namespace Vacation
{
    struct holiday
    {
        public string destination;
        public int days;
        public double cost;
    }

    public partial class MainForm : Form
    {
        StreamReader inputFile;
        holiday[] vacationList;
        holiday entry;
        int count;

        public MainForm()
        {
            InitializeComponent();

            vacationList = new holiday[20];
            entry = new holiday();
            count = 0;
        }

        private void vacation_Load(object sender, EventArgs e)
        {
            getData();

            populateData();

        }
        public void getData()
        {
            try
            {
                inputFile = File.OpenText("vacations.txt");  

                string line;
                
                while (!inputFile.EndOfStream)
                {
                    line = inputFile.ReadLine();

                    string[] token = line.Split(',');

                    entry.destination = token[0];
                    entry.days = int.Parse(token[1]);
                    entry.cost = double.Parse(token[2]);

                    vacationList[count] = entry;

                    count++;
                }
                inputFile.Close();

            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public void populateData()
        {
            for(int i = 0; i < vacationList.Length; i++)
            {
                if(vacationList[i].destination != null)
                  vacationListBox.Items.Add(vacationList[i].destination);
            }
        }

        private void showButton_Click(object sender, EventArgs e)
        {
            if(vacationListBox.SelectedIndex == -1)
            {
                MessageBox.Show("Please select a destination");
            }
            else
            {
                displayVacationInfo();
            }

        }
        public void displayVacationInfo()
        {
            destinationOutput.Text = vacationList[vacationListBox.SelectedIndex].destination;
            stayOutput.Text = vacationList[vacationListBox.SelectedIndex].days.ToString();
            costOutput.Text = vacationList[vacationListBox.SelectedIndex].cost.ToString("c");
        }
        
        private void addButton_Click(object sender, EventArgs e)
        {
            if (count == 20)
            {
                MessageBox.Show("Exceeded Maximum Vacation entries");
            }
            else
            {
                vacationForm vac = new vacationForm(this);
                vac.ShowDialog();
            }
        }
        public void addDestination(vacationAdd vac)
        {
            entry.destination = vac.Location;
            entry.days = vac.Length;
            entry.cost = vac.Cost;

            vacationList[count] = entry;
            vacationListBox.Items.Add(vacationList[count].destination);
            count++;
        }
        public void clearAll()
        {
            destinationOutput.Text = "";
            costOutput.Text = "";
            stayOutput.Text = "";

            vacationListBox.ClearSelected();
            showButton.Focus();
        }

        private void clearButton_Click(object sender, EventArgs e)
        {
            clearAll();
        }

        private void exitButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}

Output:
output1sem7
output2sem7
output3sem7output4sem7
The result of the text file after vacations has been added:
output5sem7

C#: Shape Inheritance

Shape.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Shape
{
    public abstract class shape
    {
        string _name;

        public shape()
        {
            _name =  "";
        }

        public shape(string name)
        {
            _name = name;
        }

        public string name 
        {
            get{return _name;}
        }

        public abstract double perimeter { get; }

        public abstract double area { get; }

        public abstract string dimensions { get; }
    }
}

Square.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Shape
{
    public class square : shape
    {
        double _side;

        public square(string name, double side)
            : base(name)
        {
            _side = side;
        }

        public override double area
        {
            get { return _side * _side; }
        }
        public override double perimeter
        {
            get { return 4 * _side; }
        }
        public override string dimensions
        {
            get { return "side: " + _side; }
        }
    }
}


House.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Shape
{
    public class house : shape
    {
        double _length;
        double _width;
        double _radius;

        public house(string name, double length, double width, double radius)
            : base(name)
        {
            _length = length;
            _width = width;
            _radius = radius;
        }

        public override double area
        {
            get { return _length * _width + (Math.PI * Math.Pow(_radius, 2))/ 2; }
        }
        public override double perimeter
        {
            get { return 2 * _width + (2 * Math.PI * _radius)/2 + _radius; }
        }
        public override string dimensions
        {
            get { return "Radius: " + _radius + "\nLength: " + _length + "\nWidth: " + _width; }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

Rectangle.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Shape
{
    public class rectangle : shape
    {
        double _length;
        double _width;

        public rectangle(string name, double length, double width)
            : base(name)
        {
            _length = length;
            _width = width;
        }

        public override double area
        {
            get { return _length * _width; }
        }
        public override double perimeter
        {
            get { return 2 * _length + 2 * _width; }
        }
        public override string dimensions
        {
            get { return "Length: " + _length + "\nWidth: " + _width; }
        }
    }
}

Circle.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Shape
{
    public class circle : shape
    {
        double _radius;

        public circle(string name, double radius)
            : base(name) //base is like super() except outside method
        {       
            _radius = radius;
        }

        //methods in base class must have an override
        public override double area
        {
            get { return Math.PI * Math.Pow(_radius, 2);}
        }
        public override double perimeter
        {
            get { return 2 * Math.PI * _radius; }
        }
        public override string dimensions
        {
            get { return "Radius: " + _radius; }
        }
    }
}

Main Form

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
/****    
*
* Name: Michael Peng
* Student Number: T00055798
* Seminar Number: 8
* Due Date: March 31, 2015
*
* Program Purpose:  Allows user to learn more information about a shape,
*                  displays the dimensions, area and peremiter of user selected shape
*
****/

namespace Shape
{
    public partial class mainForm : Form
    {
        shape[] shapeArray;
        public mainForm()
        {
            InitializeComponent();

            shapeArray = new shape[8];
        }
        private void mainForm_Load(object sender, EventArgs e)
        {
            createShapes();
            displayShapes();
        }
        public void createShapes()
        {
            shapeArray[0] = new circle("Circle1", 6.6);
            shapeArray[1] = new circle("Circle2",2.0);
            shapeArray[2] = new square("Square1", 6.6);
            shapeArray[3] = new square("Square2", 2.0);
            shapeArray[4] = new rectangle("Rectangle1",2.0, 6.6);
            shapeArray[5] = new rectangle("Rectangle2",2.0, 5);
            shapeArray[6] = new house("House1",2.0, 6, 4);
            shapeArray[7] = new house("House2",2.4, 2, 3);
        }
        public void displayShapes()
        {
            for(int i = 0; i < shapeArray.Length; i++)
            {
                shapeListbox.Items.Add(shapeArray[i].name);
            }
        }
        private void showButton_Click(object sender, EventArgs e)
        {
            if (shapeListbox.SelectedIndex == -1)
            {
                MessageBox.Show("Please select a shape");
            }
            else
            {
                displayDetails();
            }
        }
        public void displayDetails()
        {
            int index = shapeListbox.SelectedIndex;
            
            dimensionLabel.Text = shapeArray[index].dimensions;
            perimeterLabel.Text = shapeArray[index].perimeter.ToString("#.##");
            areaLabel.Text = shapeArray[index].area.ToString("#.##");           
        }

        private void clearButton_Click(object sender, EventArgs e)
        {
            areaLabel.Text = "";
            dimensionLabel.Text = "";
            perimeterLabel.Text = "";
            shapeListbox.SelectedIndex = -1;

            shapeListbox.Focus();
        }
        private void exitButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }

Output:

output1sem8
output2sem8

C++: Card Program

Card.cpp



// Card class definition in a separate file from main so that we may use this in all the programs now
#include <iostream>
#include <string> // class card uses C++ standard string class
#ifndef CARD_H
#define CARD_H

using namespace std;
// Card class definition

static string faces[13] = {"Ace","Two","Three","Four","Five",
                                "Six","Seven","Eight","Nine",
                                "Ten","Queen","Jack","King"};

static string suits[4] = {"Diamonds","Clubs","Hearts","Spades"};

class Card
{
private:
    int suit;
    int face;
    //static string faces[13];
    //static string suits[4];

public:
   // constructor initializes card with two ints supplied as argument
   explicit Card( int _suit, int _face )
      : suit( _suit ),
        face ( _face )// member initializer to initialize courseName
   {
      // empty body
   } // end Card constructor


    string toString()
    {
        return faces[face] + " of " + suits[suit];
    }
}; // end class Card
#endif // CARD_H

DeckOfCards.cpp


// Card class definition in a separate file from main so that we may use this in all the programs now
#include <iostream>
#include <string> // class card uses C++ standard string class
#include "Card.cpp"
#include <vector>

using namespace std;
// Card class definition

class DeckOfCards
{
private:
    vector<Card> deck;
    int currentCard, location;

public:
   // constructor initializes card with two ints supplied as argument
   DeckOfCards(): currentCard(0) {
        for(int i = 0; i < 13; i++){
            for(int j = 0; j < 4; j++){
                Card card(j,i);
                deck.push_back(card);
                currentCard++;
            }
        }
   }

   //randomize the deck
    void shuffle(){
        for(int i=0;i<52;i++)
        {
            location=rand()%52+1;
            //swap
            Card holder=deck[location];
            deck[location]=deck[i];
            deck[i]=holder;
        }
    }

    //loop through deck using currentCard
    void dealCard(){
        Card returnCard = deck[currentCard];
        cout << returnCard.toString() << endl;
        currentCard--;
    }

    //check if the currentCard is 0, if it is there are no more cards
    bool moreCards(){
        if(currentCard == 0)
            return false;
        else
            return true;
    }

}; // end class Card

CardDriver.cpp


#include <iostream>
#include <stdexcept> // for invalid_argument exception class
#include "Card.cpp"
#include "DeckOfCards.cpp"
using namespace std;
/*
CardDriver.cpp

test program for DeckOfCards.cpp which uses Card.cpp

*/
int main ()
{

    DeckOfCards deck;
    deck.shuffle();
    string empty1 = deck.moreCards()? "false" : "true";
    cout << "Is the deck empty?: " << empty1 << endl;

    cout << "Deal all the cards:" << endl;
    //while there are more cards in the deck, deal
    while(deck.moreCards())
        deck.dealCard();

    empty1 = deck.moreCards()? "false" : "true";
    cout << "Is the deck empty?: " << empty1 << endl;

};


Output
output