Wednesday, November 5, 2014

Batting Average class Examples(Evening)

Here is the BattingAverage class

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

namespace BattingAverageCalculator
{
    class BattingAverage
    {
        //fields
        private int hits;
        private int atBats;
     

        //public properties for the fields
        public int AtBats
        {
            //the get returns the value of the field
            //lets the calling class see it
            get { return atBats; }
            //the set lets the calling class
            //change the value of the underlying field
            //value is a built in variable
            set { atBats = value; }
        }
        public int Hits
        {
            get { return hits; }
            set { hits = value; }
        }

        public double CalculateBattingAverage()
        {
            //this method calculates the Batting Average
            return ((double)Hits / AtBats) * 1000;
           
        }
        



    }
}


Here is the Display class

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

namespace BattingAverageCalculator
{
    class Display
    {
        //declare the BattingAverage Calss
        private BattingAverage ba; 

        //this is the constructor
        //it is called when the class 
        //is made new
        public Display()
        {
            //instantiate (load into memory) 
            //the BattingAverage class
            //
            ba= new BattingAverage();
            //call the GetInput() method
            GetInput();
        }
        private void GetInput()
        {
            //Get the input
            Console.WriteLine("Enter the total at bats");
            //assign the input to the set of the AtBats
            //Property in the BattingAverage class
            ba.AtBats = int.Parse(Console.ReadLine());

            //do the same for the Hits property
            Console.WriteLine("Enter the total hits");
            ba.Hits = int.Parse(Console.ReadLine());

            //call the ShowBattingAVerageMethod
            ShowBattingAverage();

        }

        private void ShowBattingAverage()
        {
            //display the Batting average by calling
            //the CalculateBattingAverage() method
            //in BattingAverage (ba)
            Console.WriteLine("The batting average is " 
                + ba.CalculateBattingAverage());

            
        }
    }
}


Here is the Program

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

namespace BattingAverageCalculator
{
    /********************
     * The program class contains the main
     * It really should do nothing
     * but call the class that starts the program
     * *******************/
    class Program
    {
        static void Main(string[] args)
        {
            //Call the display Class (runs the constructor)
            Display d = new Display();
            Console.ReadKey();
        }
    }

}

Monday, November 3, 2014

First Class Example (Evening)

Here is the Mileage Class

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

namespace ClassExamples
{
    //fields --class level variables that describe the class
    //properties--make field accessible
    //methods--what the class does
    //constructors--initializing the class

 

    class Mileage
    {
        /************************
         * this class calcuates simple mileage
         * it is more work that you need 
         * for such a simple calulation but it shows
         * the basic parts and concepts of a class
        ***************************/
        //private fields 
        private double gallons;
        private double miles;

        //we have two constructors
        //constructors are methods that
        //initialize the class
        //you can have as many constructors
        //as make sense as long as they
        //have distinct signatures
        //you can only initialize a class
        //one way at a time, so a user
        //has to decide which constructor
        //to invoke
        public Mileage()
        {
            //initialize values
            Miles = 0;
            gallons = 1;
        }
        //overloaded constructor that takes two arguments
         public Mileage(double miles, double gallons)
        {
             //initialize values to what has been passed in
             //through the constructor's parameters
            Miles = miles;
            Gallons = gallons;
        }
        //public properties. A property "encapsulates"
        //a private field and exposes it to other
        //classes to see or change
        public double Miles
        {
            //lets the user see the value
            get { return miles; } 
            //lets the user change the value
            set { miles = value; }
        }

        public double Gallons
        {
            set 
            { 
                //one can do validation in a property
                if(value <=0)
                {
                    //an exception is an error message
                    //we can create our own
                    //because there is no way to display
                    //the error message in this class
                    //we throw it back to where the set
                    //message is called--in our case
                    //the Main() method in Program
                    Exception ex = new Exception("Enter a valid number for gallons");
                    throw ex;
                }
                else { 
                    //if the value is good just assign it to the field
                gallons = value;
                }
            }
            get { return gallons; }
        }

        //public method
        public double CalculateGasMileage()
        {
            return Miles / Gallons;
        }

    }
}

Here is the Program class

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

namespace ClassExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            //try catches "try" all the code. When they encounter
            //an error they fall immediately to the catch
            //skipping any lines after the error.
           try
            {
            Console.WriteLine("Enter the Miles traveled");
            double miles = double.Parse(Console.ReadLine());
            Console.WriteLine("Enter the gallons");
            
                double gallons = double.Parse(Console.ReadLine());
               //this uses the overloaded constructor of Mileage
                Mileage mileage = new Mileage(miles, gallons);
               //we call the CalculateGasMileage method
               //of the MileageClass
                Console.WriteLine("You MPG is " + mileage.CalculateGasMileage().ToString());
            }
            catch(Exception ex)
            {
                //this is a general catch. It will catch any error message 
                //and display the error object's message
                //you can do more that display error messages in a catch
                //You can redirect the code or do things to manage
                //the error
                Console.WriteLine(ex.Message);
                Console.ReadKey();
                return;
            }

           
            Console.ReadKey();
        }
    }
}

Tuesday, October 28, 2014

Gas Mileage with Methods(Morning)

Here is the program in Main

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

namespace GasMileageCalculator
{
    class Program
    {
        /***********
         * this program will calculate
         * miles per gallon given 
         * an input of mile and gallons
         * ***************/
        static void Main(string[] args)
        {
            //program variables
            double miles;
            double gallons;
            double mpg;
            bool goodMiles;
            bool goodGallons;

            //we use a do loop and a try parse to make sure the entry is
            //in the correct format
            do
            {
              
                Console.WriteLine("How many miles were traveled");
                //the try parse returns a bool true or false
                //if good it assigns the result to the out parameter miles
                //if false it assigns 0 to miles
                goodMiles = double.TryParse(Console.ReadLine(), out miles);
                if (!goodMiles)
                {
                    Console.WriteLine("Enter a valid mileage as numbers");
                }//end if

            } while (!goodMiles); //end do

            do
            {

                Console.WriteLine("How many Gallons");
                goodGallons = double.TryParse(Console.ReadLine(), out gallons);
                if (!goodGallons)
                {
                    Console.WriteLine("Enter a valid  number for Gallons");
                } //end if

            } while (!goodGallons); //end do

            mpg = miles / gallons;

            Console.WriteLine("You got {0:F2} miles per gallon", mpg);
            //Console.WriteLine("You got " + mpg.ToString("#0.00") + " miles per gallon");
            //Math.Round(mpg, 2);
            
            Console.ReadKey();


        }//end main
    }//end class
}//end namespace

Here is the program with methods

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

namespace GasMileageMethods
{
    class Program
    {
        /// 
        /// this program calculates miles but
        /// breaks it into methods
        /// GetMiles() prompts the user for miles
        /// GetGallons() prompts the user for gallons
        /// CalculateMPG() calcualtes the miles per gallon
        /// Display(double mileage) displays the results
        /// the mileage is passed to display as a
        /// parameter from CalculateMPG()
        /// 
        /// 
        static void Main(string[] args)
        {
            //load the program class into memory
            Program p = new Program();
            //call the Method to calculate the mpg
            p.CalculateMPG();
            //call the end program method
            p.EndProgram();
        }

        /// 
        /// this method prompts the user for miles
        /// it uses a try parse and a do loop
        /// to check if its a valid entry
        /// 
        /// miles
        private double GetMiles()
        {
            double miles;
            bool goodMiles;
            do
            {
                Console.WriteLine("Enter the miles traveled");
                goodMiles = double.TryParse(Console.ReadLine(), out miles);
                if (!goodMiles)
                {
                    Console.WriteLine("Enter a valid number for miles");
                }//end if
            } while (!goodMiles);//end while

            return miles;
        }//end GetMiles

        /// 
        /// This method prompts the use for Gallons 
        /// and uses a try parse and a do loop to check
        /// for the validy of the answer
        /// 
        /// gallons
        private double GetGallons()
        {
            double gallons;
            bool goodGallons;
            do
            {
                Console.WriteLine("Enter the Gallons used");
                goodGallons = double.TryParse(Console.ReadLine(), out gallons);
                if (!goodGallons)
                {
                    Console.WriteLine("Enter a valid number for Gallons");
                }//end if
            } while (!goodGallons);//end while

            return gallons;
        }//end GetGallons

        /// 
        /// the calculate method calls the GetMiles()
        /// and the GetGallons() method to  get
        /// the values and then calculated the miles 
        /// per gallon. It passes the variable storing the
        /// result to the 
        /// 
        private void CalculateMPG()
        {
            double distance = GetMiles();
            double gas = GetGallons();
            double mpg = distance / gas;
            //double mpg=GetMiles()/GetGallons();
            Display(mpg);
        }//end CalculateMPG

        private void Display(double mileage)
        {
            Console.WriteLine("You mileage is " + mileage.ToString("F2"));
        }//end Display

        private void EndProgram()
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }//

    }//end class
}

Thursday, October 23, 2014

Parallel arrays and methods (morning)

This is the second in class example. I will post the first one soon

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

namespace parallelArrays
{
    class Program
    {
        /// 
        /// This program shows how to use 
        /// parallel arrays and methods.
        /// Parallel arrays are arrays in which
        /// related values are kept on identical 
        /// indexes. [0] =[0], [1]=[1] etc.
        /// the methods are broken into 
        /// CreateArrays which declares the arrays
        /// Populate arrays which loops through the
        /// arrays and lets the user enter values
        /// CalculateArea multiplies the parallel values
        /// (values with the same index in the two arrays)
        /// Each area is passed to the display method
        /// 
        /// 
        static void Main(string[] args)
        {
            //make the program new (load into memory)
            Program p = new Program();
            p.CreateArrays(); //call the CreateArrays program
            p.EndProgram(); //call end program

        }

        private void CreateArrays()
        {
            //declare the arrays
            int[] height = new int[5];
            int[] width = new int[5];

            //call PopulateArrays and pass the two arrays to it
            PopulateArrays(height, width);
        }

        private void PopulateArrays(int[] height, int[] width)
        {

            //loop through the arrays and prompt
            //the user to provide values
            for(int i = 0; i < height.Length; i++)
            {
                Console.WriteLine("Please enter Height");
                height[i] = int.Parse(Console.ReadLine());
                Console.WriteLine("Please enter Width");
                width[i] = int.Parse(Console.ReadLine());
            }
            //call CalculateAreas and pass the arrays
            CalculateAreas(height, width);
            
        }
        private void CalculateAreas(int[] height, int[]width)
        {
            Console.BackgroundColor = ConsoleColor.DarkBlue;
            Console.Clear();
            //this loop multiplys the parallel values
            //from the arrays to get the area
            //then passes each area to the Display method()
            for(int i = 0; i<height.Length;i++)
            {
                int area=height[i] * width[i];
                DisplayArea(area);
            }
        }

        private void DisplayArea(int area)
        {
            
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("the area is : " + area.ToString());
        } 
        private void EndProgram()
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
}


Monday, October 20, 2014

Mehtods and Arrays (Evening Class)

Here is the code we did in class with comments

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

namespace ShoppingList
{
    class Program
    {
      
        /// <summary>
        /// This program we are going to
        /// enter a shopping list into an array
        /// have a second array to store the prices
        /// and third array to store discounts.
        /// these parrallel arrays
        /// Use methods and only use the Main
        /// to start the program
        /// </summary>

        int number; //this variable has class scope
        //meaning it can be seen by any method
        //in the class
        static void Main(string[] args)
        {
            //initialize the program
            Program p = new Program();
            //call the Start method
            p.Start();
            //call the end program method
            p.EndProgram();
        }

        /// <summary>
        /// the start method starts the program by
        /// calling the PopulateArrays method (which
        /// calls the create arrays methods and the 
        /// display method). It also puts that method
        /// into a while loop so that the program can be
        /// run as many times as the user would like
        /// </summary>
        private void Start()
        {
            //set the variable for the while loop
            string shopping = "yes";
            //loop as long as the shopping variable equals yes
            while (shopping.Equals("yes"))
            {
                //call the PopulateArraysMethod
                PopulateArrays();
                //ask user whether to continue or not
                Console.WriteLine("Continue Yes--any other = no");
                shopping = Console.ReadLine().ToLower();
            }
        }

        /// <summary>
        /// This array gets the number of items
        /// that the user wants to enter
        /// number is a class level variable
        /// and can be seen by any method
        /// </summary>
        private void GetNumberOfItems()
        {
            Console.WriteLine("How many items do you want to enter");
            number = int.Parse(Console.ReadLine());
        }

        /// <summary>
        /// This method declares and initializes
        /// an array for the shopping list
        /// it returns a string[] array
        /// </summary>
        /// <returns>string[]</returns>
        private string[] CreateShoppinglist()
        {
            
            string[] shoppingList = new string[number];
            return shoppingList;
        }

        //creates and returns an array for prices
        private double[] CreatePriceList()
        {
            double [] priceList = new double[number];
            return priceList;
        }

        //creates and returns an array for discounts
        private double[] CreateDiscountList()
        {
            double[] discountList = new double[number];
            return discountList;
        }

        /// <summary>
        /// this is the main method of the program
        /// it call the methods that create the arrays
        /// it loops through the arrays and lets
        /// the user enter values. the arrays are 
        /// parallel in that item [0] is parallel to price [0]
        /// is parallel to discount[0] etc.
        /// When the arrays are populated it passes
        /// them to the calculate method
        /// </summary>
        private void PopulateArrays()
        {
            //call GetNumberOfItems method to 
            //make sure number has a value
            GetNumberOfItems();
            //get the arrays created from the
            //methods that create  and return the arrays
            string[] itemList = CreateShoppinglist();
            double[] prices = CreatePriceList();
            double[] discounts = CreateDiscountList();

            //loop through the arrays and prompt
            //the user to enter values
            //by doing the three together we keep 
            //the index values in parallel
            for(int i=0;i<number;i++)
            {
                Console.WriteLine("enter the item name");
                itemList[i] = Console.ReadLine();
                Console.WriteLine("Enter the item price");
                prices[i] = double.Parse(Console.ReadLine());
                Console.WriteLine("enter any discount as a decimal");
                discounts[i] = double.Parse(Console.ReadLine());
            }
            //call the Calculate method and pass the arrays
            //as parameters. parameters are passed 1st to 1st, 
            //2nd to second, etc. the program only knows if
            //the data type is right, not if it is the correct value
            Calculate(itemList, prices, discounts);
        }

        /// <summary>
        /// This method takes the three arrays as
        /// parameters and loops through them
        /// determing the price. It does this by
        /// subtracting the discount amount from
        /// the give price (price=price - (price * discount)
        /// then it gets the name of the item from the
        /// items array and concatinates it with the price
        /// and passes the string to the Display()
        /// method where it is printed to the console
        /// </summary>
        /// <param name="items"></param>
        /// <param name="prices"></param>
        /// <param name="discounts"></param>
        private void Calculate(string[] items, double[] prices, double[] discounts)
        {
            double price = 0;
            for(int i = 0; i< number; i++)
            {
                //get the price by taking the price from the given
                //index of the array and subtracting the price * discount 
                //taken from the same index in discount array
                price = prices[i] - (prices[i] * discounts[i]);
                //put the name and the new price into a string
                //ToString() is a method that converts a number
                //to a string. The "C" formats it as currency
                string itemString = items[i] + " " + price.ToString("C");
                //call the display method and pass it the string
                //as a parameter
                Display(itemString);
            }
        }
        /// <summary>
        /// this method takes a string as a parameter
        /// and writes it to console
        /// </summary>
        /// <param name="itemPrice"></param>
        private void Display (string itemPrice)
        {
            Console.WriteLine(itemPrice);
        }
        private void EndProgram()
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }

    }
}

BookReview ERD

Here is an ERD (Entity Relation Diagram) of the BookReview database. I did not include all the attributes for each table. Note the One to One relationship between Reviewer and Login.

You can click the image to get a larger view

Comments on relationships:

There is a many to many relationship between Book and Author. Each book can have many authors, each author can have many books. To resolve this we need to create a linking table BookAuthor that matches author with book. I made the key for the linking table a composite key that contains both the BookKey and the AuthorKey. This makes it so the same author can't be cited twice for the same book. The pair always must be unique.

The relationship between Category and Book is also many to many and requires a linking table: BookCategory.

The review table is tied to the reviewer and the book table. Both are one to many. One book can be reviewed many times. On reviewer can review many books.

Comments are related to Review and Reviewer in the same way. On Review can have many comments and one Reviewer can make many comments.

There is one other table related to Reviewer. LoginTable stores the username and password for the Reviewer. The LoginTable has one child which is the LoginLog that logs every time a reviewer logs in.

Wednesday, October 15, 2014

First Methods (Evening)

Here are our two examples of using methods

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

namespace MethodsExample
{
    class Program
    {
        /// 
        /// This class shows the use of methods
        /// specifically it shows the use of methods
        /// that have a return type of int
        /// steve 10/15/2014 Evening
        /// 
    
        static void Main(string[] args)
        {
            //instantiate the program by making it new
            //because main is static it is loaded into
            //memory automatically, but the rest
            //of the class is not. Making it new
            //loads it into memory. p is the local variable name
            //of the class. The dot stands for membership
            //p.Display() calls the GetDisplay()
            //method which is a member of Program
            Program p = new Program();
            
            // I only need to call the Display method because
            //it calls the GetSum() method and the GetSum()
            //method calls the GetNumber() method. 
            p.Display();
            p.EndProgram();
        }

       
        //the get number method gets the user's input
        //of a number and returns that number
        private int GetNumber()
        {
            Console.WriteLine("Enter Number");
            int number = int.Parse(Console.ReadLine());
            return number;
        }
        //this method gets two numbers and adds them.
        //Notice it calls the GetNumber() method twice
        //this is an example of reuse. We only have to write
        //the method once. but can use it whenever we need
        //it. The GetNumber() method returns an integer
        //so the addition is not adding the methods it is adding
        //the integers returned by the method
        private int GetSum()
        {
            int sum = GetNumber() + GetNumber();
            return sum;
        }

        private void Display()
        {
            //Call GetSum to get the sum and display it
            int sum = GetSum();
            Console.WriteLine("the sum is " + sum);
        }


        private void EndProgram()
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
       
    }//end class
}

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

namespace MethodsWithParameters
{
    class Program
    {
        /// 
        /// This class shows the use of methods
        /// and passes values as parameters
        /// from one method to another.
        /// Specifically, it gets the diameter of
        /// a circle in one method, passes it to 
        /// a separate method for calculation
        /// and then to a final method for display
        /// steve  10/15/2014 Evening class
        /// 
        /// 
        //declare a constant for PI
        private const double PI = 3.14156;
        static void Main(string[] args)
        {
            //instantiate the program by making it new
            //because main is static it is loaded into
            //memory automatically, but the rest
            //of the class is not. Making it new
            //loads it into memory. p is the local variable name
            //of the class. The dot stands for membership
            //p.GetDiameter() calls the GetDiameter()
            //method which is a member of Program
            Program p = new Program();
            p.GetDiameter();
            //call end program method
            p.EndProgram();
        }

        private void GetDiameter()
        {
            //ask the user for the diameter
            Console.WriteLine("Please give the diameter of your circle");
            double diameter = double.Parse(Console.ReadLine());

            //call the GetCirucumerance method and pass it
            //diameter as a parameter
            GetCircumference(diameter);
        }

        //GetCircumference method which takes a parameter
        //that is a double in type
        private void GetCircumference(double diam)
        {
            double circumference = diam * PI;

            //call Display and pass it the Circumference
            Display(circumference);
        }

        private void Display(double circ)
        {
            //display the parmater that was passed
            Console.WriteLine("the circumference is " + circ);
        }

        private void EndProgram()
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }//end class
}