C#入门经典课后习题答案.pdf

上传人:文*** 文档编号:88910850 上传时间:2023-05-04 格式:PDF 页数:81 大小:6.81MB
返回 下载 相关 举报
C#入门经典课后习题答案.pdf_第1页
第1页 / 共81页
C#入门经典课后习题答案.pdf_第2页
第2页 / 共81页
点击查看更多>>
资源描述

《C#入门经典课后习题答案.pdf》由会员分享,可在线阅读,更多相关《C#入门经典课后习题答案.pdf(81页珍藏版)》请在得力文库 - 分享文档赚钱的网站上搜索。

1、Beginning Visual C#2005Exercise AnswersChapter 1:Introducing C#No Exercises.Chapter 2:Writing a C#ProgramNo Exercises.Chapter 3:Variables and ExpressionsExercise 1Question:In the following code,how would we refer to the name g reat from code inthe namespace fabulous?namespace fabulous(/code in fabul

2、ous namespacenamespace super(namespace smashing(/great name defined)Answer:super.smashing.greatExercise 2Question:Which of the following is not a legal variable name:a)myVariablelsGoodb)99Flakec)_floord)tim e2G etJiggyW idlte)wrox.coinAnswer:b because it starts with a numberande because it contains

3、a full stopExercise 3Question:Is the string su p ercalif ra g ilistic e x p ia lid o c io u s too big to fit ina s trin g variable?Why?Answer:No,there is no theoretical limit to the size of a string that may be contained in astrin g variable.Exercise 4Question:By considering operator precedence,list

4、 the steps involved in the computationof the following expression:resultVar+=varl*var2+var3 var4/var5;Answer:The*and/operators have the highest precedence here,followed by+,andfinally+=.The precedence in the exercise can be illustrated using parentheses as follows:resultVar+=(varl*var2)+var3)10)A(va

5、r2 10)Exercise 2Question:Write an application that includes the logic from Exercise 1,obtains twonumbers from the user and displays them,but rejects any input where both numbers aregreater than 10 and asks for two new numbers.Answer:static void Main(string args)(bool numbersOK=false;double varl,var2

6、;varl=0;var2=0;while(!numbersOK)IConsole.WriteLine(Give me a number:);varl=Convert.ToDouble(Console.ReadLine();Console.WriteLine(Give me another number:*);var2=Convert.ToDouble(Console.ReadLine();if(varl 10)A(var2 10)(numbersOK=true;ielse(if(varl=10)&(var2 10)&(var2 10)(Console.WriteLine(Only one nu

7、mber may be greater than10.);)else(numbersOK=true;)Console.WriteLine(You entered 0 and 1.,varl,var2);Exercise 3Question:What is wrong with the following code?int i;for(i=1;i=10;i+)(if(i%2)=0)continue;Console.WriteLine(i);Answer:The code should read:int i;for(i=1;i=imagMax;imagCoord+=imagStep)for(rea

8、lCoord=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.6;coord.real=1.77;coord.real+=0.03)(iterations=0;temp.real=coord.real;temp.imag=c

9、oord.imag;arg=(coord.real*coord.real)+(coord.imag*coord.imag);while(arg 4)&(iterations=0;index一一)(reversedString+=myStringindex;Console.WriteLine(Reversed:0,reversedString);Exercise 6Question:Write a console application that accepts a string and replaces all occurrences ofthe string no with yes.Answ

10、er:static void Main(string args)(Console.WriteLine(Enter a string:);string myString=Console.ReadLine();myString=myString.Replace(no,yes);Console.WriteLine(Replaced no with yes:0,myString);Exercise 7Question:Write a console application that places double quotes around each word in astring.Answer:stat

11、ic void Main(string args)(Console.WriteLine(Enter a string:);string myString=Console.ReadLine();myString=+myString.Replace(*,*)+Mn;Console.WriteLine(Added double quotes areound words:0*,myString);Or using S trin g.S p lit():static void Main(string args)(Console.WriteLine(Enter a string:);string mySt

12、ring=Console.ReadLine();string myWords=myString.Split(*);Console.WriteLine(Adding double quotes areound words:);foreach(string myWord in myWords)Console.Write(0”,myWord);Chapter 6:FunctionsExercise 1Question:The following two functions have errors.What are they?static bool Write()(Console.WriteLine(

13、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(*0 n/i);Answer:The first function has a return type of bool,but doesn*t return a bool value.The second function has a params ar

14、gument,but this argument isnt at the endof the argument list.Exercise 2Question:Write an application that uses two command line arguments to place valuesinto a string and an integer variable respectively,then display these values.Answer:static void Main(string args)(if(args.Length!=2)Console.WriteLi

15、ne(Two arguments required.);return;string paraml=args0;int param2=Convert.ToInt32(args1);Console.WriteLine(String parameter:0”,paraml);Console.WriteLine(Integer parameter:0”,param2);Note that this answer contains code that checks that 2 arguments have been supplied,which wasnt part of the question b

16、ut seems logical in this situation.Exercise 3Question:Create a delegate and use it to impersonate the C onsole.ReadLine()function when asking for user input.Answer:class Classi(delegate string ReadLineDelegate();static void Main(string args)(ReadLineDelegate readLine=newReadLineDelegate(Console.Read

17、Line);Console.WriteLine(Type a string:);string userinput=readLine();Console.WriteLine(You typed:0”,userinput);)Exercise 4Question:Modify the following s tru c t to include a function that returns the total priceof an order:struct order(public string itemName;public int unitCount;public double unitCo

18、st;Answer:struct order(public string itemName;public int unitCount;public double unitCost;public double TotalCost()(return unitcount*unitCost;)Exercise 5Question:Add another function to the order struct that returns a formatted string asfollows,where italic entries enclosed in angle brackets are rep

19、laced by appropriate values:Order Information:items at$each,total cost$.Answer:struct orderpublic string itemName;public int unitCount;public double unitcost;public double TotalCost()(return unitcount*unitcost;public string Info()(return Order information:+unitCount.ToString()+itemName+items at$+uni

20、tCost.ToString()+each,total cost$+TotalCost().ToString();Chapter 7:Debugging and Error HandlingExercise 1Question:Using Trace.W riteLine()is preferable to using Debug.W riteLine()as the Debug version only works in debug builds.Do you agree with this statement?Why?Answer:This statement is only true f

21、or information that you want to make available in allbuilds.More often,you will want debugging information to be written out only whendebug builds are used.In this situation,the Debug.W riteLine()version is preferable.Using the Debug.W riteLine()version also has the advantage that it will not becomp

22、iled into release builds,thus reducing the size of the resultant code.Exercise 2Question:Provide code for a simple application containing a loop that generates an errorafter 5(X)0 cycles.Use a breakpoint to enter break mode just before the error is caused onthe 5000th cycle.(Note:a simple way to gen

23、erate an error is to attempt to access a nonexistent array element,such as myArray 1000 in an array with a hundred elements.)Answer:static void Main(string args)Ifor(int i=1;i 10000;i+)(Console.WriteLine(Loop cycle 0,i);if(i=5000)Console.WriteLine(args999);In the preceding code a breakpoint could be

24、 placed on the following line:Console.WriteLine(Loop cycle 0,i);The properties of the breakpoint should be modified such that the hit count criterion isbreak when hit count is equal to 5000”.Exercise 3Question:fin a lly code blocks only execute if a catch block isnt executed.True orfalse?Answer:Fals

25、e.Finally blocks always execute.This may occur after a catch block hasbeen processed.Exercise 4Question:Given the enumeration data type o rie n ta tio n defined below,write anapplication that uses SEH to cast a byte type variable into an o rie n ta tio n typevariable in a safe way.Note that you can

26、force exceptions to be thrown using thechecked keyword,an example of which is shown below.This code should be used inyour application.enum orientation:byte(north=1,south=2,east=3,west=4myDirection=checked(orientation)myByte);Answer:static void Main(string args)(orientation myDirection;for(byte myByt

27、e=2;myByte 10;myByte+)(try(myDirection=checked(orientation)myByte);if(myDirection orientation.west)throw new ArgumentOutOfRangeException(myByte,myByte,Value must be between 1and 4);catch(ArgumentOutOfRangeException e)(/If this section is reached then myByte 4.Console.WriteLine(e.Message);Console.Wri

28、teLine(Assigning default value,orlentation.north.);myDirection=orientation.north;Console.WriteLine(myDirection=0”,myDirection);Note that this is a bit of a trick question.Since the enumeration is based on the b y te typeany b y te value may be assigned to it,even if that value isnt assigned a name i

29、n theenumeration.In the preceding code you generate your own exception if necessary.Chapter 8:Introduction to Object-OrientedProgrammingExercise 1Question:Which of the following are real levels of accessibility in OOP?FriendPublicSecurePrivateProtectedLooseWildcardAnswer:Public,private,and protected

30、 are real levels of accessibility.Exercise 2Question:You must call the destructor of an object manually,or it will waste memory.True or False?Answer:False.You should never call the destructor of an object manuallythe.NETruntime environment will do this for you during garbage collection.Exercise 3Que

31、stion:Do you need to create an object in order to call a static method of its class?Answer:No,you can call static methods without any class instances.Exercise 4Question:Draw a UML diagram similar to the ones shown in this chapter for thefollowing classes and interface:An abstract class called HotDri

32、nk that has the methods Drink(),AddMilk(),andAddSugar(),and the properties Milk and Sugar.An interface called I Cup that has the methods Ref i l l ()and Wash(),and theproperties Color and Volume.A class called CupOfCof fee that derives from HotDrink,supports the ICupinterface,and has the additional

33、property BeanType.A class called CupOfTea that derives from HotDrink,supports the ICup interface,and has the additional property Leaf Type.Answer:Exercise 5Question:Write some code for a function that would accept either of the two cup objectsin the above example as a parameter.The function should c

34、all the AddMilk(),Drink(),and Wash()methods for the cup object it is passed.Answer:static void ManipulateDrink(HotDrink drink)drink.AddMilk();drink.Drink();ICup cupinterface=(ICup)drink;cupinterface.Wash();Note the explicit cast to ICup.This is necessary as HotDrink doesnt support the ICupinterface,

35、but you know that the two cup objects that might be passed to this function do.However,this is dangerous,as other classes deriving from HotDrink.are possible,whichmight not support ICup,but could be passed to this function.To correct this you shouldcheck to see if the interface is supported:static v

36、oid ManipulateDrink(HotDrink drink)(drink.AddMiIk();drink.Drink();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 1Question:What is wrong with the following code?public sealed class M

37、yClass(/class membersIpublic class myDerivedClass:MyClass(/class membersAnswer:myDerivedClass derives from MyClass,but MyClass is sealed and cant bederived from.Exercise 2Question:How would you define a non-creatable class?Answer:By defining all of its constructors as private.Exercise 3Question:Why

38、are non-creatable classes still useful?How do you make use of theircapabilities?Answer:Non-creatable classes can be useful through the static members they possess.Infact,you can even get instances of these classes through these members,for example:c la ss CreateMeIp riv a te CreateM e()(s ta tic p u

39、 b lic CreateMe GetCreateM e()(re tu rn new CreateM e();)The internal function has access to the private constructor.Exercise 4Question:Write code in a class library project called V ehicles that implements theV ehicle family of objects discussed earlier in this chapter,in the section on interfacesv

40、s.abstract classes.There arc 9 objects and 2 interfaces that require implementation.Answer:namespace V ehicles(public a b stra c t c la ss V ehicle(public a b stra c t c la ss Car:V ehicle(public a b stra c t c la ss T rain:V ehicle()public in te rfa c e IP assen g erC arrier(public in te rfa c e I

41、Heavy L oadcarrier(public c la ss SUV:Car,IP assen g erC arrier(public c la ss Pickup:Car,IP assen g erC arrier,IH eavyLoadCarrierpublicc la ssCompact:Car,IP assen g erC arrierpublicc la ssP assenger?rain:T rain,IP assen g erC arrierpublicc la ssF reig h tT rain :T rain,IH eavyLoadCarrierpublicc la

42、ssT424DoubleBogey:T rain,IH eavyLoadCarrierExercise 5Question:Create a console application project,T ra ffic,that referencesV ehicles.d ll(created in Question 4 above).Include a function,AddPassenger(),that accepts any object with the IP assengerC arrier interface.To prove that the codeworks,call th

43、is function using instances of each object that supports this interface,callingthe ToString()method inherited from System.O bject on each one and writing theresult to the screen.Answer:using System;using V ehicles;namespace T ra fficc la ss C lassis ta tic void M a in(strin g args)AddPassenger(new C

44、ompact();AddPassenger(new SUV();AddPassenger(new P ickup();AddPassenger(new P assen g erT rain();s ta tic void A ddP assenger(IP assengerC arrier V ehicle)C onsole.W riteL ine(V ehicle.T o S trin g();Chapter 10:Defining Class MembersExercise 1Question:Write code that defines a base class,MyClass,wit

45、h the virtual methodG etString().This method should return the string stored in the protected fieldm yString,accessible through the write only public property C ontainedString.Answer:class MyClass(protected string myString;public string ContainedString(set(myString=value;public virtual string GetStr

46、ing()(return myString;Exercise 2Question:Derive a class,M yDerivedClass,from MyClass.Override theG etS tring()method to return the string from the base class using the baseimplementation of the method,but add the textH(output from derived c la s s)Hto the returned string.Answer:class MyDerivedClass:

47、MyClass(public override string GetString()(return base.GetString()+“(output from derived class);Exercise 3Question:Write a class called MyCopyableClass that is capable of returning a copy ofitself using the method GetCopy().This method should use the MemberwiseClone()method inherited from System.Ob

48、je c t.Add a simple property to the class,and writeclient code that uses the class to check that everything is working.Answer:class MyCopyableClass(protected int mylnt;public int Containedlnt(get(return mylnt;set(myInt=value;)public MyCopyableClass GetCopy()(return(MyCopyableClass)MemberwiseClone();

49、And the client code:class Classi(static void Main(string args)(MyCopyableClass objl=new MyCopyableClass();objl.Containedlnt=5;MyCopyableClass obj2=objl.GetCopy();objl.Containedlnt=9;Console.WriteLine(obj2.Containedlnt);This code displays 5,showing that the copied object has its own version of the my

50、lntfield.Exercise 4Question:Write a console client for the C hlO C ardL ib library that draws 5 cards at atime from a shuffled Deck object.If all 5 cards are the same suit then the client shoulddisplay the card names on screen along with the text F lu s h!,otherwise it should quitafter 50 cards with

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 教育专区 > 教案示例

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知得利文库网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号-8 |  经营许可证:黑B2-20190332号 |   黑公网安备:91230400333293403D

© 2020-2023 www.deliwenku.com 得利文库. All Rights Reserved 黑龙江转换宝科技有限公司 

黑龙江省互联网违法和不良信息举报
举报电话:0468-3380021 邮箱:hgswwxb@163.com