《C#入门经典习题答案.pdf》由会员分享,可在线阅读,更多相关《C#入门经典习题答案.pdf(78页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、Exercise SolutionsChapter 1:Introducing C#No exercises.Chapter 2:Writing a C#ProgramNo exercises.Chapter 3:Variables and ExpressionsExercise 1Q.In the following code,how would you refer to the name great from code in the namespacefab u lo u s?namespace fabulous(/code in fabulous namespace)namespace
2、super(namespace smashing/great name definedA.super.sm ashing.greatExercise 2Q.Which of the following is not a legal variable name?a.m yV ariablelsG oodb.99Flakec._ f lo o rd tim e2G etJiggy W id lte A.b.Because it starts with a number,and,e Because it contains a full stop.Exercise 3Q.Is the string s
3、 u p e r c a lif r a g i li s ti c e x p ia l id o c i o u s too big to fit in a s t r in gvariable?Why?A.No,there is no theoretical limit to the size of a string that may be contained in a strin g variable.Exercise 4Q.By considering operator precedence,list the steps involved in the computation of
4、the followingexpression:resu ltV ar+=v a rl*var2+var3%var4/var5;A.The*and/operators have the highest precedence here,followed by+,%,and finally+=.Theprecedence in the exercise can be illustrated using parentheses as follows:resu ltV ar+=(v arl*var2)+var3)%(var4/v ar5);Exercise 5Q.Write a console app
5、lication that obtains four in t values from the user and displays their product.A.s ta tic void M ain(strin g args)(in t firstN um ber,secondNumber,thirdNumber,fourthNumber;C onsole.W riteLine(G ive me a number:0);firstN um ber=C onvert.Tolnt32(C onsole.R eadLine();C onsole.W riteLine(Give me anothe
6、r number:);secondNumber=C onvert.T oInt32(Console.ReadLine();C onsole.W riteL ine(nGive me another number:H;thirdNumber=C onvert.T olnt32(Console.ReadLine();C onsole.W riteLine(G ive me another number:);fourthNumber=C onvert.T oInt32(Console.ReadLine();C onsole.W riteLine(The product of 0,1,2,and 3
7、is 4.n,firstN um ber,secondNumber,thirdNumber,fourthNumber,firstN um ber*secondNumber*thirdNumber*fourthNumber);)Note that C o n v e rt.T o ln t3 2 ()is used here,which isnt covered in the chapter.Chapter 4:Flow ControlExercise 1Q.If you have two integers stored in variables v a r l and v a r2,what
8、Boolean test can you performto see if one or the other(but not both)is greater than 10?A.(v a r l 1 0)人(v ar2 10)Exercise 2Q.Write an application that includes the logic from Exercise 1,obtains two numbers from the user,and displays them,but rejects any input where both numbers are greater than 10 a
9、nd asks for twonew numbers.A.s ta tic void M ain(strin g args)bool numbersOK=false;double varl,var2;varl=0;var2=0;while(!numbersOK)(Console.WriteLine(Give me a number:);varl=Convert.ToDouble(Console.ReadLine();Console.WriteLine(Give me another number:*);var2=Convert.ToDouble(Console.ReadLine();if(va
10、rl 10)A(var2 10)(numbersOK=true;else(if(varl=10)&(var2 10)&(var2 10)(Console.WriteLine(Only one number may be greater than 10.”);elseInumbersOK=true;Console.WriteLine(You entered 0 and 1.,varl,var2);Exercise 3.What is wrong with the following code?int i;for(i=1;i=10;i+)if(i%2)=0)continue;Console.Wri
11、teLine(i);The code should read:intfori;(i=1;i=imagMax;imagCoord+=imagStep)for(realCoord=realMin;realCoord=realMax;realCoord+=realStep)(iterations=0;realTemp=realCoord;imagTemp=imagCoord;arg=(realCoord*realCoord)+(imagCoord*imagCoord);while(arg 4)&(iterations=-1.2;coord.imag-=0.05)(for(coord.real=-0.
12、6;coord.real=1.77;coord.real+=0.03)(iterations=0;temp.real=coord.real;temp.imag=coord.imag;arg=(coord.real*coord.real)+(coord.imag*coord.imag);while(arg 4)&(iterations=0;index一)(reve rsedSt ring+=myStringindex;Console.WriteLine(Reversed:0z reversedString);Exercise 6Q.Write a console application that
13、 accepts a string and replaces all occurrences of the string no withyes.A.static void Main(string args)(Console.WriteLine(nEnter a string:n);string myString=Console.ReadLine();myString=myString.Replace(Hno,yes);Console.WriteLine(Replaced nno with nyesM:0”,myString);Exercise 7Q.Write a console applic
14、ation that places double Quotes around each word in a string.static void Main(string args)Console.WriteLine(Enter a string:n);string myString=Console.ReadLine();myString=n+myString.Repl ace(,n)+n n;Console.WriteLine(Added double quotes areound words:0n,myString);Or using String.Split():static void M
15、ain(string args)(Console.WriteLine(Enter a string:n);string myString=Console.ReadLine();string myWords=myString.Split();Console.WriteLine(Adding double quotes areound words:H);foreach(string myWord in myWords)(Console.Write(n0n”,myWord);Chapter 6:FunctionsExercise 1Q.The following two functions have
16、 errors.What are they?static bool Write()(Console.WriteLine(Text output from function.);static void myFunction(string label,params int args,bool showLabel)(if(showLabel)Console.WriteLine(label);foreach(int i in args)Console.WriteLine(0n,i);A.The first function has a return type ofbool,but doesnt ret
17、urn a bool value.The second function has aparam s argument,but it isnt at the end of the argument list.Exercise 2Q.Write an application that uses two command line arguments to place values into a string and aninteger variable respectively,then display these values.A.static void Main(string args)(if(
18、args.Length!=2)(Console.WriteLine(Two arguments required.);return;)string paraml=args0;int param2=Convert.Tolnt32(args1);Console.WriteLine(String parameter:0”,paraml);Console.WriteLine(nInteger parameter:0”,param2);Note that this answer contains code that checks that 2 arguments have been supplied,w
19、hichwasnt part of the Question but seems logical in this situation.Exercise 3Q.Create a delegate and use it to impersonate the Console.ReadLine()function when askingfor user input.A.class Program|delegate string ReadLineDelegate();static void Main(string args)(ReadLineDelegate readLine=new ReadLineD
20、elegate(Console.ReadLine);Console.WriteLine(Type a string:n);string userinput=readLine();Console.WriteLine(nYou typed:0“,userInput);Exercise 4Q.Modify the following struct to include a function that returns the total price of an order:struct orderpublic stringpublic intpublic doublestruct orderpubli
21、c stringpublic intpublic doubleitemName;unitcount;unitCost;itemName;unitCount;unitCost;public double TotalCost()(return unitCount*unitCost;Exercise 5Q.Add another function to the order struct that returns a formatted string as follows,where italicentries enclosed in angle brackets are replaced by ap
22、propriate values:Order Information:items at$each,totalcost$s tru c t orderpublic s trin g itemName;public in t unitC ount;public double u n itc o st;public double T otalC ost()(retu rn unitC ount*unitC ost;)public s trin g Info()(retu rn nOrder inform ation:+unitC ount.T oS tring()+”+itemName+n item
23、 s a t$”+u n itc o st.T o S trin g()+n each,to ta l cost$”+T otalC ost().T o S trin g();)Chapter 7:Debugging and Error HandlingExercise 1Q.t4Using T race.W rite L in e ()is preferable to using D ebug.W rite L in e ()because theDebug version only works in debug buildsZ,Do you agree with this statemen
24、t?Why?A.This statement is only true for information that you want to make available in all builds.Moreoften,you will want debugging information to be written out only when debug builds are used.Inthis situation,the D ebug.W rite L in e ()version is preferable.Using the Debug.W rite L in e ()version
25、also has the advantage that it will not be compiled intorelease builds,thus reducing the size of the resultant code.Exercise 2Q.Provide code for a simple application containing a loop that generates an error after 5000 cycles.Use a breakpoint to enter Break mode just before the error is caused on th
26、e 5000th cycle.(Note:asimple way to generate an error is to attempt to access a nonexistent array element,such asm yA rray 1000 in an array with a hundred elements.)A.s ta tic void M ain(strin g args)(fo r(in t i=1;i 10000;i+)(Console.W riteLine(Loop cycle 0,i);i f (i=5000)(C onsole.W riteL ine(args
27、999);In VS,a breakpoint could be placed on the following line:C onsole.W riteLine(nLoop cycle 0”,i);The properties of the breakpoint should be modified such that the hit count criterion is“breakwhen hit count is equal to 5000.In VCE,a breakpoint could be placed on the line that causes the error beca
28、use you cannot modifythe properties of breakpoints in VCE in this way.Exercise 3Q.f in a l ly code blocks execute only if a c a tc h block isnt executed.True or false?A.False,f i n a l l y blocks always execute.This may occur after a c a t ch block has been processed.Exercise 4Q.Given the enumeratio
29、n data type o r i e n ta t io n defined in the following code,write anapplication that uses Structured Exception Handling(SEH)to cast a byte type variable into ano r i e n ta t io n type variable in a safe way.(Note:you can force exceptions to be thrown usingthe c h eck ed keyword,an example of whic
30、h is shown here.This code should be used in yourapplication.)enum o rie n ta tio n :byte(north=1,south=2,e a st=3,west=4)myDirection=checked(orientation)m yB yte);A.s ta tic void M ain(strin g args)(o rie n ta tio n m yD irection;fo r(byte myByte=2;myByte 10;myByte+)(try(m yD irection=checked(orient
31、ation)m yB yte);i f (myDirection o rie n ta tio n.w e st)throw new ArgumentOutOfRangeException(myByte,myByte,Value must be between 1 and 4);)catch(ArgumentOutOfRangeException e)(/I f th is sectio n is reached then myByte 4.C onsole.W riteLine(e.M essage);C onsole.W riteLine(A ssigning d e fa u lt va
32、lue,o rie n ta tio n.n o rth.);m yD irection=o rie n ta tio n.n o rth;C onsole.W riteLine(m yD irection=0n,m yD irection);This is a bit of a trick question.Because the enumeration is based on the byte type any bytevalue may be assigned to it,even if that value isnt assigned a name in the enumeration
33、.In thiscode you generate your own exception if necessary.Chapter 8:Introduction to Object-Oriented ProgrammingExercise 1Q.Which of the following are real levels of accessibility in OOP?a.Friendb.Publicc.Secured.Privatee.Protectedf.Looseg.WildcardA.(b)public,(d)private,and(e)protected are real level
34、s of accessibility.Exercise 2Q.You must call the destructor of an object manually,or it will waste memory.True or False?A.False.You should never call the destructor of an object manually.The.NET runtime environmentdoes this for you during garbage collection.Exercise 3Q.Do you need to create an objec
35、t to call a static method of its class?A.No,you can call static methods without any class instances.Exercise 4Q.Draw a UML diagram similar to the ones shown in this chapter for the following classes andinterface:*An abstract class called HotDrink that has the methods Drink(),AddMilk(),andAddSugar(),
36、and the properties Milk,and Sugar.*An interface called I Cup that has the methods Re f i 11(and Wash(),and theproperties C olor and Volume.*A class called CupOfCof fee that derives from HotDrink,supports the iCup interface,and has the additional property BeanType.*A class called CupOfTea that derive
37、s from HotDrink,supports the 工Cup interface,andhas the additional property LeafType.A.fg AA01.xxxExercise 5Q.Write some code for a fijnction that would accept either of the two cup objects in the aboveexample as a parameter.The function should call the AddMilk(),Drink(),and Wash()methods for and cup
38、 object it is passed.A.static void ManipulateDrink(HotDrink drink)(drink.AddMilk();drink.Drink();ICup cupinterface=(ICup)drink;cupinterface.Wash();Note the explicit cast to ICup.This is necessary because HotDrink doesnt support the ICupinterface,but we know that the two cup objects that might be pas
39、sed to this function do.However,this is dangerous because other classes deriving from HotDrink are possible,which might notsupport ICup,but could be passed to this function.To correct this,check to see if the interface issupported:static void ManipulateDrink(HotDrink drink)(drink.AddMilk();drink.Dri
40、nk();if(drink is ICup)(ICup cupinterface=drink as ICup;cupinterface.Wash();The is and as operators used here are covered in Chapter 11.Chapter 9:Defining ClassesExercise 1Q.What is wrong with the following code?public sealed class MyClass(/Class members.public class myDerivedClass:MyClass(/Class mem
41、bers.A.m yDerivedClass derives from MyClass,but MyClass is sealed and cant be derived from.Exercise 2Q.How would you define a none rentable class?A.By defining it as a static class or by defining all of its constructor as private.Exercise 3Q.Why are noncreatable classes still useful?How do you make
42、use of their capabilities?A.Noncreatable classes can be useful through the static members they possess.In fact,you can evenget instances of these classes through these members.Heres an example:class CreateMe(private CreateMe()(static public CreateMe GetCreateMe()(return new CreateMe();Here the publi
43、c constructor has access to the private constructor as it is part of the same classdefinition.Exercise 4Q.Write code in a class libraiy project called Vehicles that implements the Vehicle family ofobjects discussed earlier in this chapter,in the section on interfaces versus abstract classes.Thereare
44、 nine objects and two interfaces that reQuire implementation.A.For simplicity,the following class definitions are shown as part of a single code file rather thanlisting a separate code file for each.namespace Vehicles(public abstract class Vehicle(public abstract class Car:Vehicle(public abstract cl
45、ass Train:Vehicle()public interface IPassengerCarrier()public interface IHeavyLoadCarrier()public class SUV:Car,IPassengerCarrier()public class Pickup:Car,IPassengerCarrier,IHeavyLoadCarrier(public class Compact:Car,IPassengerCarrierpublic class PassengerTrain:Train,IPassengerCarrier)public c la ss
46、F reightT rain:T rain,IHeavyLoadCarrier()p ublic class T424DoubleBogey:T rain,IHeavyLoadCarrier()Exercise 5Q.Create a console application project,Traffic,that references V e h ic le s .d l 1(created in Exercise4).Include a function,AddPassenger(),that accepts any object with theIP a s s e n g e rC a
47、 rrie r interface.To prove that the code works,call this function using instancesof each object that supports this interface,calling the ToString()method inherited fromS ystem.O b je c t on each one and writing the result to the screen.A.using System;using V ehicles;namespace T raffic(c la ss Progra
48、m(s ta tic void M ain(strin g(args)(AddPassenger(new Compact();AddPassenger(new SUV();AddPassenger(new P ickup();AddPassenger(new P assengerT rain();s ta tic void A ddPassenger(IPassengerC arrier V ehicle)(C onsole.W riteLine(V ehicle.T oS tring();)Chapter 10:Defining Class MembersExercise 1Q.Write
49、code that defines abase class,M yC lass,with the virtual method G e tS trin g ().Thismethod should return the string stored in the protected field m y S trin g,accessible through thewrite only public property C o n ta in e d S trin g.A.class MyClass(p ro tected strin g myString;p ublic strin g C ont
50、ainedString(se tm yString=v alu e;p u b lic v ir tu a l s tr in g G e tS trin g()(re tu rn m yString;Exercise 2Q.Derive a class,M y D e riv e d C la ss,from M yC lass.Overnde the G e tS tr in g ()method toreturn the string from the base class using the base implementation of the method,but add the t