CS365 Midterm

advertisement
CS365 Midterm
1)
2)
3)
4)
1.
You must answer all of the questions.
Place your name on the exam.
You must use Java to implement the coding questions.
Good luck!
(22points)Choosetheappropriatetermfromthefollowinglisttofillineach
blankbelow:
abstract
type
executable
abstract
class
extends
class
friend
inheritance interface
jar
module
nonvirtual
protected
namespace
parametric private
composition concrete
type
generic
hash
tables
java
jump
tables
Object
objectoriented
public
pure
virtual
static
subclass
Throwable
throws
…
Error
Exception
implementation
implements
library
longjmp
overloading
package
replicated
Runtime
Exception
superclass
virtual
setjmp
shared
source
subtype
supertype tar
template
types
virtual
void
vtables
machine
a. parametricpolymorphismusestemplatesinstantiatedwithtypeswhile
subtypepolymorphismmakesuseofclasshierarchiestosupport
polymorphism.
b. Replicatedinheritancereferstomultipleinheritanceinwhichasubclass
receivesmultiplecopiesofanysharedsuperclasses.
c. C++attemptstoprovidesomeofthebenefitsofpackages/modulesthrough
itsnamespaceandfriendmechanisms.
d. Avirtualmachineisaninterpreterthatsimulatestheexecutionofa
machinebyexecutingthemachine'sinstructionsetusingsoftwarepieceof
softwarethatsimulatesmachineinstructions
e. ExceptionIfyoucreateauser-definedexceptionclassinJava,whichJava
classshoulditsubclass?
f. InJava,aninterfaceisusedtodeclarea(n)abstracttype.
g. vtablesareusedtoimplementvirtualmethodsatrun-time
h. longjmpTheCfunctionthattakesstoredstateinformationandanerror
codeasarguments,andthatthrowscontrolbacktothecallingfunctionby
poppingthestackandrestoringthestateinformationofthecallingfunction.
i. AjarfileinJavaallowsacollectionofclassestobebundledtogetherand
treatedlikeasinglefileforexecution,muchlikeabinaryfileinC/C++.
2. (3points)SupposethatclassGoowantstorestrictaccesstoitsinstance
variablesizeto1)anyclassinitspackageand2)anysubclass,whetherthat
subclassisinGoo’spackageoranotherpackage.Whataccessprotectionshould
theprogrammerassigntosize?
a. private
b. protected
c. package
d. public
3. (4points)SupposeyouhavethefollowingC++classes:
ClassFruit{…}
ClassMelon:publicFruit{…}
ClassCantelope:publicFruit{…}
FurtherassumethatFruitisanabstractclassbecauseithasoneormore
purevirtualmethods.Circleallallofthefollowingdeclarationsthatarelegal:
a. Fruitf;
b. Fruitf=Fruit();
c. Fruitf=Melon();
d. Fruit*f=newFruit();
e. Fruit*f=newMelon();
f. Fruit*f=newCantalope();
4. (20points--Generics)WriteaJavatemplateclassnamedStackthattakesa
singletypeparameternamedEandsupportsthreemethods:
a. aconstructorthatinitializesthestack.
b. pop:takesnoparameters,removesthefirstvaluefromthetopofthestack
andreturnsit.Ifthestackisemptyitshouldthrowaninstanceofaclass
namedStackEmptybacktothecallingfunction.Youdonotneedtoknowthe
particularsofStackEmptyandyoushouldassumethatthatclassalready
exists.
c. push:avoidmethodthattakesasingleparameteroftypeEandassignsitto
thetopofthestack.
classStack<E>{
classStackNode<E>{
Evalue;
StackNode<E>next;
}
StackNode<E>top;
Stack(){
top=null;
}
Epop()throwsStackEmpty{
if(top==null)
thrownewStackEmpty();
EreturnValue=top.value;
top=top.next;
returnreturnValue;
}
voidpush(Eitem){
StackNode<E>newNode=newStackNode<E>();
newNode.value=item;
newNode.next=top;
top=newNode;
}
}
5. (21points--Inheritance)Supposethatyouaredesigningtheinputportionofa
Javaapplication.Theapplicationshouldbeabletoreadfromthe1)console,2)a
file,or3)awidgetsuchasatype-intextbox.Youhavebeengiventhefollowing
specifications:
• Regardlessofwhichinputobjectyouareusing,theapplicationneedsto
beabletoopen/closetheobject(openandclosemethodsthattakeno
parametersandreturnvoid).
• Theapplicationneedstobeabletoreadatextstringfromaninputobject
(readmethodthatreturnsastringandtakesnoparameters).
• TheclassesforthereaderobjectsshouldbeConsoleReader,FileReader,
andTextReader.
• Theopenandclosemethodsarethesameforeachofthethreeclassesbut
thereadmethodisdifferentforeachclass.
a. DeclareaninterfacenamedReadersothatobjectsofanyofthethree
classescanbeassignedtoaReadervariable.Forexample:
ReadermyReader=newConsoleReader();
interfaceReader{
voidopen();
voidclose();
Stringread();
}
b. Designanddrawaclasshierarchyfortheabovethreeobjectsusing
Java.
• Nexttoeachclasslistthemethodsthatyouwoulddeclarewith
thatclass.Youshouldlistamethodwithaclassonlyifyouwould
provideanimplementationforthatmethodinthatclass.
• Putanasterisknexttoanymethodthatshouldbedeclared
abstract
AbstractReader
open
close
read*
|
------------------------------------------|
|
|
ConsoleReader
FileReader
TextReader
read
read
read
SincetheimplementationforopenandcloseisthesameforallthreeReader
objects,youshouldcreateasuperclassthatdeclaresandprovidesan
implementationforthesetwomethods.Thereadmethoddoesnothavetobe
declaredinAbstractReader,butinthatcaseyoumustensurethat
ConsoleReader,FileReader,andTextReaderallimplementtheReader
interface.
c. ProvideJavaclassdeclarationsforanysuperclassesthatyoucreatedin(b)
andforConsoleReader.
a. TheclassesmustimplementtheReaderinterface
b. Youshouldnotshowanyimplementation.Forexample,todeclarea
voidmethodnamedfoo,write:
publicvoidfoo();
abstractclassAbstractReaderimplementsReader{
publicvoidopen(){...}
publicvoidclose(){...}
abstractpublicStringread();
}
classConsoleReaderextendsAbstractReader{
publicStringread(){...}
}
orifyouchoosenottodeclarethereadmethodin
AbstractReader:
classAbstractReader{
publicvoidopen(){...}
publicvoidclose(){...}
}
classConsoleReaderextendsAbstractReaderimplementsReader
{
publicStringread(){...}
}
Notethatthelattersolutionisnotasgoodbecauseyoucanactually
createaninstanceofAbstractReader,whichisundesirable.You
cannotfixtheproblembydeclaringAbstractReadertobeabstract,
sincetheJavacompilerwillcomplain.
6. (25points--JavaProgramming)WriteacompleteJavaprogram,including
importstatementsinaclasscalledGraderthatmeetsthefollowing
specifications:
a. TheclassshouldbepartofthepackageGrade.
b. Usetheconstructortoimplementwhateveryouwouldnormallyimplement
inmaininaC++program.Theconstructorshouldtakeasinglestring
argumentwhichisthenameofthegradefile.
c. Yourprogramshouldreadscoresandstudentnamesfromagradefilewhose
namehasbeenprovidedasacommandlineargumentandforeachstudentit
shouldprintthestudent’snameandaveragescoretostdout.Theaverage
shouldbecomputedasanintegeraverage.Forexample,ifthestudent’s
scoresare7and10,thentheprintedaverageshouldbe8.
d. YourconstructorshouldnothandletheIOExceptionthatmaybegenerated
byopeningthefilebutyourmainmethodshouldcatchtheexceptionand
printtheexception’smessagebyinvokingitsgetMessage()method.
Eachlineofthegradefilelistsastudent'snameandthenthestudent’sscores.The
gradefilemayhavemultiplestudents.Forexample:
Baby Daisy 59 75 93 53
Smiley The Amazing Hound 86 45 100 63 78 91
Chipmunk 45
Notethatanamemayconsistofanarbitrarynumberofwordsandthatastudent
mayhaveanarbitrarynumberofscores.
Youroutputshouldbeformattedasfollows:
1. Thenameshouldbeleft-justifiedinafield30characterswide.
2. Theaverageshouldberight-justifiedinafield3characterswide.
3. Thereshouldbeaspacebetweenthetwofields.
Fortheaboveinput,yourprogramwouldproducetheoutput:
Baby Daisy
Smiley The Amazing Hound
Chipmunk
70
77
45
Hereissomeadditionalinformation:
1. Youareguaranteedthat:
• thereisatleastonescoreforeachstudent,
• thatallscoresarenon-negativeintegers,and
• thateverylinestartswithatleastoneword.
2. TheAPIfortheScannerclasshasbeenprovidedattheendofthisexam.
3. YoushouldusetheFileReaderclassforafile.YoudonotneedtheAPIforthe
FileReaderclassinordertocompletethisproblem.
4. TheScannerclassisinJava’sutillibraryandtheFileReaderclassisinJave’s
iolibrary
packageGrade;
importjava.util.Scanner;
importjava.io.*;
classGrader{
Grader(Stringfilename)throwsIOException{
Scannerreader=newScanner(newFileReader(filename));
Scannertokenizer;
Stringline,name;
intsum,count;
while(reader.hasNextLine()){
line=reader.nextLine();
tokenizer=newScanner(line);
name=tokenizer.next();
while(!tokenizer.hasNextInt()){
name=name+""+tokenizer.next();
}
sum=0;
count=0;
while(tokenizer.hasNextInt()){
sum+=tokenizer.nextInt();
count++;
}
tokenizer.close();
System.out.printf("%-30s%3d%n",name,sum/count);
}
}
staticpublicvoidmain(Stringargs[]){
try{
newGrader(args[0]);
}
catch(IOExceptione){
System.out.println(e.getMessage());
}
}
}
7. (5points:ExecutingaJavaProgram)Answerthefollowingquestionsabout
thepreviousproblem.
a) WhatisthenameofthefileinwhichGradershouldbeplaced?
Grader.java
b) WhatisthenameofthedirectoryinwhichGrader’sfileshouldbeplaced?
Grade
c) SupposethatIaminanarbitrarydirectoryandthatthedirectorycontaining
Grader’sfileisstoredinadirectorynamed/home/bvz/labs.Furtherassume
thatthegradefileisnamedinput.txt.Writethefulljavacommandrequired
toexecutetheGraderprogramthatyouwroteinthepreviousquestion.
Anyofthefollowinganswersareacceptable:
java–cp.:../home/bvz/labsGrade.Graderinput.txt
java–cp/home/bvz/labsGrade.Graderinput.txt
java–classpath.:../home/bvz/labsGrade.Graderinput.txt
java–classpath/home/bvz/labsGrade.Graderinput.txt
-cpisanabbreviationfor–classpath.Youalsodon’thavetoincludethe
.:..prefixsinceyouknowthattheGradepackageisin/home/bvz/labs.
Download