Thursday, April 10, 2014

Q 1 CHAPTER 10 ACTIVITY BOOK REGISTRATION

Q 1) Write an application that creates a class named Registration. The application would be used by the counselors
     of an IT education center, while registering students. The registration data entry
     is done differently for carrer registration and for modular registration. Your application
     should have seperate class for the two categories of students. In case of modular registration. Your application
     should have seperate class for two categories of students. In case of Modular registration, you need to record the student's prior
     experience or knowledge.

     Hint: Use delegate in the registration class while registering a student to call the appropriate methods.


Ans 1)
 
     using System;
     namespace DelegateApp
     {
          class DelegateExample
         {
              public abstract class Student{ }
              public void Modular : Student
               {
                   public void GetExperience()
                   {
                      string name;
                      string experience;
                      Console.WriteLine("Enter your name:")
                      name = Console.ReadLine();
                      Console.WriteLine("Enter the experience of the student in the year:");
                      experience = Console.ReadLine();
                      Console.WriteLine("\n{0} has {1} years experience", name, experience);
                     
                   }
                   }
                    public class General : Student
                   {
                        public void Aptitute()
                    {
                        string name;
                        string marks;
                        Console.WriteLine("\nEnter your name: ");
                        name = Console.ReadLine();
                        Console.WriteLine("Enter the marks of the aptitude test:");
                        marks = Console.ReadLine();
                        Console.WriteLine("\n{0} has got {1} marks in the aptitude test", name, marks);
                    }
                    }
                        public class Registration
                     {
                         public delegate void RegistrationType();
                         public RegistrationType Register;
                         public void DoRegistration(RegistrationType R)
                     {
                         Register = R;
                      }
                         public void DoNextRegistration()
                      {
                         if(Register ! = null)
                          {
                              Register();
                          }
                           }
                          }

                         static void Main(string[] args)
                          {
                             string s;
                             Console.WriteLine("Enter the registration type(Carrer/Modular): ");
                             s = Console.ReadLine().ToUpper();
                             Registration Reg = new Registration();
                             Modular Mod = new Modular();
                             General Gen = new General();
                             if( s== "MODULAR")
                          {
                             Reg.DoRegistration(new Registratin.RegistrationType(Mod.GetExperience));
                             Reg.DoNextRegistration();
                             else if (s == "CAREER")
                          {
                             Reg.DoRegistration(new Registration.RegistrationType(Gen.Aptitute));
                             Reg.DoNextRegistration();
                           }
                              else
                              Console.WriteLine("Invalid registration type");
                              Console.ReadLine();
                           }
                           }}




















                 

                     

Q 1 CHAPTER 9 ACTIVITY BOOK THREADING TOLL BRIDGE

question 1:-

Write an application to simulate the vehicles crossing a toll bridge on a motorway. For the purpose of this exercise, simulate the environment for five vehicles that are approaching the bridge and the toll booth.
 The vehicles are numbered from one to five. The vehicles have to go through the following five stages: Start the journey Arrive at the toll Enter the toll booth Exit the toll booth Cross the bridge The vehicles can be in any of the stages in parallel,
 except the third stage as only one vehicle can enter the toll booth at a time. The simulation is performed by having one thread for each vehicle, and consists of the following classes: Vehicle: Simulates the behavior of a vehicle. TollBooth: Simulates the behavior of a toll booth. Simulate:
 Creates the vehicles and controls the simulation.

Ans:-

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

namespace ConsoleApplication1
{
    public class vehical
    {
        private int id;
        private static TollBooth = new TollBooth();
        public vehicle(int id)
        {
            this.id=id;
        }
        public void exec()
        {
            Console.WriteLine("vehicle {0} starts journey",id+1);
            Random RandGen = new Random();
            int Rnd=RandGen .Next(0,100);
            travel (Rnd);
            Console.WriteLine("vehicle {0} arrives at the toll ", id+1);
            toll.useToll(this);
            travel (Rnd);
            Console.WriteLine("vehicle {0} has crossed the bridge ",id+1);
        }
        public int getVehicleId()
        {
            return this.id;
        }
        public void travel (int time)
        {
            int limit =500000;
            for(int j=0; j<time;j++)
            {
                for(int k =0 ; k<limit;k++)
                    (// do nothing);
                }
            }
    }
    public class TollBooth
    {
        bool inUse;
       
        public TollBooth()
        {
            inUse=false;
        }
        public void useToll(Vehicle vehicle)
        {
            if(inUse==false)
            {
                inUse=true;
                Console.WriteLine("vehicle {0} enters tollbooth ", vehicle.getVehicleId()+1);
                vehicle.travel(50);
                Console.WriteLine("Vehicle {0} exits tollbooth ",vehicle.getVehicleId()+1);
                inUse=false;
                break;
            }
        }
    }
}
public class Simulate
{
    private static int noOfVehicles =5;
    private static Vehicles[] vehicles;
    public static void Main(string[]args)
    {
        try
        {
            Simulate sm=new Simulate();
            vehicles=new Vehicles[5];
            for(int i=0;i<noOfVehicles;i++)
            {
                vehicles[i]=new Vehicles(i);
                Thread t=new Thread(new ThreadStart(vehicles[i].exec);
                t.Start();
                Thread.Sleep(100);
            }
            Console.ReadLine();
        }
        catch (Exception ex)
        {
            System.Console.WriteLine(ex);
        }
    }
}

Q 1 CHAPTER 8 ACTIVITY BOOK EXCEPTION

Question 1:-
David wants to create a ticket booking application for a movie theater. The application should ask the user for his choice, whether he wants to book the tickets or not.
 The application should also ask the user for the total number of tickets to be booked. While booking the tickets, if the total number of booked tickets exceeds the available tickets,
 the application should raise an exception and display an appropriate message. Hint: The total number of available tickets is 10.

Ans:-

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

namespace ConsoleApplication9
{
    class TicketLimit
    {
        static void Main(string[] args)
        {
            Summer Summer = new Summer();
            try
            {
                Summer.CalculateTicket();
            }
            catch (TicketLimt e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }
        }
    }
    public class TicketLimt : ApplicationException
    {
        public TicketLimt(string massage)
            : base(massage)
        {

        }
    }
    public class Summer
    {
        int TotalTickets = 10;
        int count = 0;
        char choice = 'Y';
        public void CalculatetICKET()
        {
            while (true)
            {
                Console.WriteLine("dO you want to book the tickets(Y/N)");
                choice = Convert.ToChar(Console.ReadLine());
                if (choice == 'Y' || choice == 'Y')
                {
                    Console.WriteLine("Only {0} tickets are available", TotalTickets);
                    Console.WriteLine("enter the number of tickets you want to book");
                    count = Convert.ToInt32(Console.ReadLine());
                    if (count > TotalTickets)
                        throw (new TicketLimt("Tickets not available"));
                    else
                        TotalTickets -= count;
                }
                else
                    break;
            }
        }
    }
}

Q 2 CHAPTER 7 ACTIVITY BOOK HANGMAN GAME

Q 2) you need to genrrate a program to play the hangman game.the program asks a user to enter a category as book or movie. Based on the category provided,book name or movie name is extracted from a file containing a list of book names and user is asked to guess the name by typing one character at a time.Develop the hangman game application.

ans 2)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace game
{
    class Hangman
    {
        string randomString, userString;
        int dataLength;
        string category;
        string[] bookData = new string[10];
        string[] movieData = new string[10];
        int bookCount = 0, movieCount = 0;

        public Hangman()
        {
            FillNameValues();
        }

        private void FillNameValues()
        {
            FileStream fs = new FileStream("D:\\TextTest.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
            string firstLine;
            StreamReader sRead=new StreamReader(fs);
            sRead.BaseStream.Seek(0,SeekOrigin.Begin);
            firstLine =sRead.ReadLine();

            while (firstLine!=null)
            {
                if(firstLine.Substring (0,1)=="B")
                {
                    int stringStartPos=firstLine.IndexOf(':');
                    bookData[bookCount]=firstLine.Substring(stringStartPos + 1);
                    bookCount++;
                }
                else
                {
                    int stringStartPos=firstLine.IndexOf(':');
                    movieData[movieCount]=firstLine.Substring(stringStartPos+1);
                    movieCount++;
                }
                firstLine=sRead.ReadLine();
            }
        }
        public int AcceptCategory()
        {
            Console.WriteLine("enter the catagory to play book/movie");
            category = Console.ReadLine();
            category = category.ToUpper();
            if (category != "BOOK" && category != "MOVIE")
            {
                Console.WriteLine("invalid category \n");
                return 0;
            }
            else
            {
                ExtractName();
                return 1;
            }
        }

        public void ExtractName()
        {
            Random RandGen = new Random();
            if (category == "BOOK")
            {
                int Rnd = RandGen.Next(0, bookCount - 1);
                randomString = bookData[Rnd];
            }
            else
            {
                int Rnd = RandGen.Next(0, movieCount - 1);
                randomString = movieData[Rnd];
            }
        }

        public void startGame()
        {
            dataLength = randomString .Length;
            char locateChar;
            int correcetCnt=0,inCorrectCnt=0;
            int i,k;
            char [] s=new char[randomString.Length];
            initializeUserString();
            showUserInputString();
            if(category =="BOOK")
            {
                Console.WriteLine("Thje total number of characters in the book are :{0}",randomString.Length);
                Console.WriteLine("The total number of characters you can enter to guess the name of books:{0}",randomString.Length+2);
            }
            else
            {
                Console.WriteLine("The total number of characters in the ,movie:{0}",randomString.Length);
                Console.WriteLine("The total number of characters you can enter to guess the name of movie:{0}", randomString.Length + 2);
            }
            for(i=1,k=0;i<=dataLength+2||k==dataLength;i++)
            {
                if(inCorrectCnt == dataLength || inCorrectCnt==dataLength)
                    break ;
                Console.WriteLine("Enter the character");
                locateChar=Convert.ToChar(Console.ReadLine().ToLower());
                int foundPos=0;
                int foundChar=0;
                foreach (char c in randomString)
                {
                    if(c==locateChar)
                    {
                        UpdateString(foundPos,locateChar.ToString());
                        k++;
                        foundChar=1;
                    }
                    foundPos++;
                }
                if(foundChar==0)
                {
                    inCorrectCnt++;
                }
                else
                {
                    correcetCnt++;
                }
                showUserInputString();
                Console.WriteLine("Total correct attempts {0}\t",correcetCnt);
                Console.WriteLine("Total incorrect attempts {0}\t",inCorrectCnt);
                if(k==dataLength)
                break;
            }
            if(randomString==userString)
            {
                Console.WriteLine("You have won\n");
            }
            else{
                Console.WriteLine ("the correct name is {0}", randomString);
                Console.WriteLine("you have lost\n");
            }}
        private void UpdateString(int fpos, string updatestr)
        {
            string beforeString, afterString;
            if (fpos != 0 && fpos != dataLength - 1)
            {
                if (fpos == 1)
                    beforeString = userString.Substring(0, 1);
                else

                    beforeString = userString.Substring(0, fpos);
                afterString = userString.Substring(fpos + 1, dataLength - (fpos + 1));
                userString = beforeString + updatestr + afterString;
            }
            if (fpos == 0)
            {
                afterString = userString.Substring(fpos + 1, dataLength - (fpos + 1));
                userString = updatestr + afterString;
            }
            if (fpos == dataLength - 1)
            {
                beforeString = userString.Substring(0, fpos);
                userString = beforeString + updatestr;
            }
        }
        public void initializeUserString()
        {
            userString = " ";
            for (int i = 0; i < dataLength; i++)
            {
                userString = userString.Insert(i, "*");
            }
        }
        public void showUserInputString()
        {
            Console.Clear();
            Console.WriteLine("input value: {0} \n \n", userString);
        }}
    class game
    {
        static void Main(string[] args)
        {
            Console.Clear();
            Hangman obj = new Hangman();
            int returnVal = obj.AcceptCategory();
            if (returnVal == 1)
            {
                obj.startGame();
            }
            Console.ReadLine();

        }
    }
}




texttest



book:otheloo
book:beguiled
book:macbeth
book:frankenstein
book:time
movie:renaissance
movie:matrix
movie:adrift
movie:garfield
movie:narnia

Q 1 CHAPTER 7 ACTIVITY BOOK XYZ ORG.

Question 1:-David is a team leader of XYZ organization.He wants to create a scheduler,which will store fields,such as the appointment
date,the name of thr person to meet,and time.he needs to develop an application that will enable the user to fill these fields.


ans:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Chap7_A1
{
    class Schedule
    {
        struct details
        {
            public DateTime Date;
            public string Appointment;
            public string Time;
            public string Day;
        };
        private details Testdetails;
        static FileStream F;
        StreamWriter W;
        StreamReader R;
        public void Getdata()
        {
            String Duedata;
            Console.Write("Apointment Date (MM/DD/YY) : ");
            Duedata = Console.ReadLine();

            if ((Duedata.Length) != 8)
            {
                Console.WriteLine("Incorrect format of date");
                Console.ReadLine();
                System.Environment.Exit(0);
            }
            if (((Duedata.Substring(2, 1)) != "/") || ((Duedata.Substring(5, 1)) != "/"))
            {
                Console.WriteLine("Incorrect format of date");
                Console.ReadLine();
                System.Environment.Exit(0);
            }
            try
            {
                Testdetails.Date = Convert.ToDateTime(Duedata);
            }
            catch (Exception e)
            {
                Console.WriteLine("Invalid Date");
                System.Environment.Exit(0);
            }
            Testdetails.Day =
                Convert.ToString(Testdetails.Date.DayOfWeek);
            Console.Write("Appointment with: ");
            Testdetails.Appointment = Console.ReadLine();
            Console.Write("Appoinment Time(hr:mn): ");
            Testdetails.Time = Console.ReadLine();

            if ((Testdetails.Time.Length) != 5)
            {
                Console.WriteLine("Incorrect formet of time");
                System.Environment.Exit(0);
            }
            if ((Testdetails.Time.Substring(2, 1)) != ":")
            {
                Console.WriteLine("Incorrect format of time");
                System.Environment.Exit(0);
            }
            F = new FileStream("MyFile.txt", FileMode.Append, FileAccess.Write);
            W = new StreamWriter(F);
            W.Write("Date:");
            W.Write(Testdetails.Date.ToShortDateString());
            W.Write("?");
            W.Write("Day: ");
            W.Write(Testdetails.Day);
            W.Write("?");
            W.Write("Name: ");
            W.Write(Testdetails.Appointment);
            W.Write("?");
            W.Write("Time: ");
            W.Write(Testdetails.Time);
            W.WriteLine("?");

            W.Flush();
            W.Close();
        }
        public void Display()
        {
            string Str;
            F = new FileStream("MyFile.txt",
            FileMode.OpenOrCreate, FileAccess.Read);
            R = new StreamReader(F);
            Console.Clear();
            int Pos = 0;
            while ((Str = R.ReadLine()) != null)
            {
                while (true)
                {
                    Pos = Str.IndexOf("?");
                    if (Pos == -1)
                        break;
                    Console.WriteLine(Str.Substring(0, Pos));
                    Str = Str.Substring(Pos + 1);
                }
                Pos = 0;
            }
            R.Close();
        }
        public void Search()
        {
            string Str, Chkstrl, Chkstr2;
            DateTime DD; int Pos;
            F = new FileStream("MyFile.txt", FileMode.Open,
                FileAccess.Read);
            R = new StreamReader(F);
            Console.Write("Enter Date (MM/DD/YY): ");
            DD = Convert.ToDateTime(Console.ReadLine());
            while ((Str = R.ReadLine()) != null)
            {
                Chkstrl = "Date: " + DD.ToShortDateString();
                Pos = Str.IndexOf("?");
                Chkstr2 = Str.Substring(0, Pos);
                if ((Chkstrl.CompareTo(Chkstrl)) == 0)
                {
                    while (true)
                    {
                        Pos = Str.IndexOf("?");
                        if (Pos == -1)
                            break;
                        Console.WriteLine(Str.Substring(0, Pos));
                        Str = Str.Substring(Pos + 1);
                    }
                    Pos = 0;
                }
            }
            R.Close();
        }
        static void Main(string[] args)
        {
            Schedule S = new Schedule();
            int Ch = 0;
            Console.Clear();
            while(Ch != 4)
            {
                Console.WriteLine("1. Add appointment");
                Console.WriteLine("2. View appointment");
                Console.WriteLine("3. Search");
                Console.WriteLine("4. Exit");
                Console.WriteLine("Enter Choice: ");
                Ch = Convert.ToInt32(Console.ReadLine());
                switch (Ch)
                {
                    case 1: Console.Clear(); S.Getdata();
                        Console.Clear();break;
                    case 2: Console.Clear(); S.Display();
                        Console.ReadLine(); Console.Clear(); break;
                    case 3: Console.Clear(); S.Search();
                        Console.ReadLine(); Console.Clear(); break;
                    case 4: return;
                    default: Console.WriteLine("Invalid Input."); break;}
            }
            Console.ReadLine();
        }
    }
}

Wednesday, April 9, 2014

CHAPTER 6 Q1 ACTIVITY BOOK

Q 1) Create a class, Height with two attributes, feet and inches. Include the functionality in the class to add two objects of the height class,
as shown in the following example:

Height3= Height1+ Height2;


Suppose, the object, Height1 contains the value, 5 feet 6 inches and the object, Height2 contains the value, 4 feet 8 inches; then the object Height3 should have the
value, 10 feet 2 inches.



Ans 1)

using System;
class Height
{
    double feet;
    double inches;
    public Height()
    {
        feet = 0.0;
        inches = 0.0;
    }
    public Height(double feet, double inches)
    {
        this.feet = feet;
        this.inches = inches;
    }
    public static Height operator +(Height d1, Height d2)
    {
        Height h = new Height();
        h.feet = d1.feet + d2.feet;
        h.inches = d1.inches + d2.inches;
        while(h.inches>=12.0)
        { h.feet++;
        h.inches = h.inches - 12.0;      
        }
        return h;
    }
    static void Main(string[] args)
    {
        Height d1 = new Height(12.0, 6.8);
        Height d2 = new Height(10, 18.9);
        Height d3 = new Height();
        d3 = d1 + d2;
        Console.WriteLine("Feet:" + d3.feet);
        Console.WriteLine("Inches:" + d2.inches);
        Console.ReadLine();
    }
}

Q 2 CHAPTER 5 ACTIVITY BOOK

Q 2) Smith is currently studying Bachelors in Information Technology(IT), He has an assignment to develop a program using the abstract classes, which displays the following statements:
1. I'm a Line.
2. I'm a Circle.
3. I'm a square
He has to create a Draw() method in a program to display the preceding statements. Help Smith to accomplish the task.


Ans 2)

 using System;
       namespace DrawShapes
       {
          public abstract class DrawingObject
          {
              public abstract void Draw();
          }
         
          public class Line : DrawingObject
          {
              public override void Draw()
              {
                  Console.WriteLine("I'm a Line.");
               }
              }
           
          public class Circle: DrawingObject
              {
                  public override void Draw()
                  {
                       Console.WriteLine("I'm a Circle.");
                  }
                  }
                public class Square : DrawingObject
                  {
                     public override void Draw()
                  {
                     Console.WriteLine("I'm a Square.");
                  }
                  }
                   public class DrawDemo{
                  public static int Main(string[] args)
                    {
                       DrawingObject[] dObj = new DrawingObject[3];
                     dObj[0] = new Line();
                     dObj[1] = new Circle();
                     dObj[2] = new Square();
                 
                     
                     foreach(DrawingObject drawObj in dObj)
                      {
                         drawObj.Draw();
                      }
                      Console.ReadLine();
                      return 0;
                      }
                      }
                      }