Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
Intro to Programming in Java        
600.107                 Johns Hopkins University 
 
 1 
 
Name _____________________________________        
 
 
Blackboard (JHED) login ID: __________________ 
 
 
 
Final Exam 
 
Please read all questions carefully before answering and make your answers 
legible.  You are NOT allowed any cheat sheets, calculators, computers, 
phones, or other assistance tools.  Show all work for partial credit.  The test 
is worth 100 points total. 
 
Please sign the following ethics statement. 
 
I agree to complete this exam without assistance from any person, prohibited 
tool, or other unauthorized means.  I also agree not to discuss this exam or 
its contents with anyone who has not taken their final yet. 
 
 X 
---------------------------------------------------------------------------------- 
 
This exam should not be very hard if you have a solid grasp of the concepts 
covered in the class.  Best of success to you! 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Intro to Programming in Java        
600.107                 Johns Hopkins University 
 
 2 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Intro to Programming in Java        
600.107                 Johns Hopkins University 
 
 3 
I. Short Answer [12 pts] 
 
1. [4 pts] What is the difference between the == operator and an equals method?  Why 
do we generally want to use an equals method when comparing object type variables 
as opposed to the == operator? 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2. [4 pts] What is inheritance and why would we want to use it? 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3. [4 pts] Why do we want to make various classes as opposed to putting everything into 
different methods in the one class that contains the main method? 
 
 
 
 
 
 
 
 
 
 
Intro to Programming in Java        
600.107                 Johns Hopkins University 
 
 4 
II. Shorter Answer [20 pts] 
 
1. [4 pts] Consider the following section from the definition of class OfficeBuilding. 
 
public class OfficeBuilding 
{ 
   public int sqrFeet; 
   private String name; 
   protected double cost; 
    
   public OfficeBuilding() {} 
    
   protected boolean isBuilt() 
   { 
      ... 
   } 
    
   public void moveIn()  
   { 
      ... 
   } 
    
   public double rentSpace()  
   { 
      ... 
   } 
    
   private int renovate(int days) 
   { 
      ... 
   } 
   ... 
} 
 
For the following lettered questions, just because a member (data, constructor, methods) 
is in the answer to one of the questions, does not mean it cannot be in the answer to one 
or more of the other questions. 
 
a. Which members are visible to (accessible from) OfficeBuilding and its subclasses? 
 
 
 
 
 
 
 
b. Which members are visible to (accessible from) only the OfficeBuilding class? 
 
 
 
 
 
Intro to Programming in Java        
600.107                 Johns Hopkins University 
 
 5 
c. Which members are visible to (accessible from) any class? 
 
 
 
 
 
 
 
d. Which field(s) should we write getter(s) and setter(s) for, so classes outside 
OfficeBuilding and its inheritance hierarchy can access it(them)? 
 
 
 
 
 
 
 
2. [4 pts] Consider the following instantiation, assuming Box is some pre-defined class. 
 
Box[][] grid = new Box[3][5]; 
 
a. How many Box objects can be referred to in this grid array? 
 
 
 
 
 
b. What type of variable is grid[0]? 
 
 
 
 
 
c. What type of variable is grid[1][2]? 
 
 
 
 
 
d. For any integers x and y, where x is on range [0,2] and y is on range [0,4], what is the 
initial value of grid[x][y]? 
 
 
 
 
 
 
Intro to Programming in Java        
600.107                 Johns Hopkins University 
 
 6 
3. [3 pts] What requirement must an array meet before we can use binary search on it?  
List two algorithms we might use to get an array into this required format. 
 
 
 
 
 
4. [1 pts] You have three algorithms A, B, and C, that run in worst case times O(log(n)), 
O(n), and O(n2), respectively, where n is the input size.  Only considering worst case 
running time, which algorithm would we most likely want to use? 
 
 
 
 
5. [4 pts] For each pair of classes X and Y below, put a check mark in the appropriate 
column, saying whether X should be a subclass of Y, Y should be a subclass of X, or 
there should be no inheritance; rather, one should be a member of the other (aggregation). 
 
Class X Class Y X a subclass of Y Y a subclass of X Aggregation 
Closet Skeleton    
Submarine Submersible    
Politician Senator    
Computer Laptop    
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Intro to Programming in Java        
600.107                 Johns Hopkins University 
 
 7 
6. [4 pts] Consider the following code.  The checkCountry(String) method throws 
an InvalidCountryException if the String given it is not an actual country name. 
 
Scanner kb = new Scanner(System.in); 
String initName = "Javaland"; 
String place = initName; 
try 
{ 
   System.out.println("Where in the world is Carmen Sandiego?"); 
   place = kb.nextLine(); 
   checkCountry(place); 
   System.out.println("Thank you"); 
} 
catch (InvalidCountryException ice) 
{ 
   System.out.println("That's not a country :("); 
   place = initName; 
} 
finally 
{ 
   System.out.println("She's in " + place); 
} 
 
a. On one run of the program, the user enters “Alpha Centauri” (which is not a country).  
Write the text that displays on the screen (input & output), in the order it is printed and 
typed. 
 
 
 
 
 
 
 
 
 
 
 
 
b. On another run of the program, the user enters “Canada” (which is a country).  Write 
the text that displays on the screen (input & output), in the order it is printed and typed. 
 
 
 
 
 
 
 
 
 
 
Intro to Programming in Java        
600.107                 Johns Hopkins University 
 
 8 
III. Multiple Choice [24 pts] (Please circle the letter of your choice) 
 
1. [2 pts] Which of the following is correct terminology about inheritance? 
 
A. We extend from a base class and implement an interface 
B. We implement a base class and extend from an interface 
C. We extend from a subclass and implement a base class 
D. We implement from a subclass and extend an interface 
 
 
 
2. [2 pts] Which of the following is correct? 
 
A. An object is like the blueprint, and we can have many instances of it, which are 
called classes 
B. A class is like the blueprint, and we can have many instances of it called, which 
are called objects 
C. There is no difference between a class and an object 
D. The object keyword indicates we’re defining an object and the class keyword 
indicates we’re defining a class 
 
 
 
3. [2 pts] If a variable is declared static in a particular class, what does that mean? 
 
A. It cannot be changed 
B. It can only be changed by the instances of the class in which it is declared 
C. There is only 1 copy of it that all instances of the class can access 
D. Each instance of the class has its own copy of the variable 
 
 
 
4. [2 pts] If a method is declared static in a particular class, what does that mean? 
 
A. The method cannot modify any variables 
B. It can only be called from within the class 
C. You need an instance of the class to access it, even though it can’t access instance 
variables/methods 
D. You do not need an instance of the class to access it, because it can’t access 
instance variables/methods 
Intro to Programming in Java        
600.107                 Johns Hopkins University 
 
 9 
5. [2 pts] What does just this piece of code do: Song[] music; 
 
A. Creates a new array of references to Song objects, called music 
B. Creates a new array of references to music objects, called Song 
C. Declares a variable called music whose type is an array of Song objects, but does 
not create an actual array 
D. Declares a variable called music whose type is null 
 
 
 
Questions 6 – 10 refer to the following code. 
 
1. public class Desk 
2. { 
3.    private int length; 
4.    private int width; 
5.    private int height; 
6.     
7.    public Desk(int length, int width, int h) 
8.    { 
9.       length = length; 
10.      this.width = width; 
11.      height = this.h; 
12.   } 
13.    
14.   public int getLength() { 
15.      return this.length; 
16.   } 
17.} 
 
6. [2 pts] What are the fields defined in this class? 
 
A. The three integers passed as parameters in the constructor, defined in line 7 
B. The three integers declared in lines 3-5 
C. There are none 
D. Only the ones where the this keyword is used in front of them 
 
 
 
7. [2 pts] What is line 9 doing? 
 
A. Assigning the value of the parameter length to the field length 
B. Assigning the value of the field length to the parameter length 
C. Assigning the value of the parameter length to itself, i.e. doing nothing useful 
D. Assigning the value of the field length to itself, i.e. doing nothing useful 
Intro to Programming in Java        
600.107                 Johns Hopkins University 
 
 10 
8. [2 pts] Line 10 is attempting to assign the value of width, passed into the constructor, 
to the variable width in the Desk class.  It was claimed that the this keyword is not 
needed.  Which of the following is true? 
 
A. It is needed, but the left and right hand sides of the assignment should be 
swapped, so that the equation is: width = this.width; 
B. It is needed, because we need to differentiate between the width parameter and the 
width field (use this to refer to the field one), and the assignment is correct as 
written. 
C. It is needed, because we need to differentiate between the width parameter and the 
width field (use this to refer to the parameter one), and the assignment is correct 
as written. 
D. It is not needed, and should be rewritten as: width = width; 
 
 
 
9. [2 pts] Line 11 is attempting to assign the value of h to the variable height.  It was 
claimed that there is an error in line 11.  Which of the following is true? 
 
A. The error is there’s no field h in the Desk class, so can’t write this.h.  It should be 
corrected to: this.height = h; 
B. The error is the same as specified in option A, but it should be corrected to the 
equation: h = height; 
C. The error is simply that the right and left hand sides of the assignment are 
switched.  It should be corrected to: this.h = height; 
D. There is no error. 
 
 
 
10. [2 pts] Assume that any compilation (i.e. compile time) errors in the above code are 
corrected.  If an instance of this class is made with the instantiation:  
Desk d = new Desk(1,2,3);  What is the return value of calling 
d.getLength()?  The default value of integer field variables is 0. 
 
A. 0 
B. 1 
C. 2 
D. 3 
 
 
 
Intro to Programming in Java        
600.107                 Johns Hopkins University 
 
 11 
11. [2 pts] Both abstract classes and interfaces allow you to declare method signatures 
and provide no implementation of such methods.  Why then might you use an abstract 
class as opposed to an interface? 
 
A. There’s no good reason why, they’re basically the same 
B. If you have an abstract class A you can create an instance of it like so:                          
A var = new A(); but you wouldn’t be able to do this with an interface 
C. Abstract classes can define functionality and non-constant fields that subclasses 
can use, while requiring subclasses to provide their own implementations for 
certain operations, whereas interfaces just define method signatures (and return 
types) and constants 
D. You wouldn’t, because abstract classes are only used in special situations where 
you want to prevent inheritance, since they cannot be inherited from, but you can 
inherit from interfaces 
 
 
 
12. [2 pts] You have two methods named calc in the same class that both return an 
integer, but one takes 1 double and the other takes 2 doubles.  We say method calc is: 
 
A. Overridden 
B. Overloaded 
C. Instantiated 
D. Invoked  
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Intro to Programming in Java        
600.107                 Johns Hopkins University 
 
 12 
IV. Tracing [12 pts] 
 
Consider the following classes, assuming they are in separate files. 
 
public class TradeShip 
{ 
   /** Number of pieces of cargo on the ship */ 
   private int cargo; 
   /** Weight of the ship */ 
   private int weight; 
    
   /** Creates a new ship with no cargo and no weight */ 
   public TradeShip()  
   { 
      this.cargo = 0; 
      this.weight = 0; 
   } 
    
   /** Adds the given cargo to this ship, which increases the weight by  
    * the weight of the cargo. 
    * @param c 
    *    the cargo to be added 
    * @return amount of money that can be made by selling this cargo 
    */ 
   public int addCargo(Cargo c) 
   { 
      this.weight += c.getWeight(); 
      this.cargo++; 
      return c.getWeight() * 2 + (this.cargo % 2); 
   } 
   
   public String toString() 
   { 
      return "TradeShip has " + this.cargo +  
         " pieces of cargo and weighs " + this.weight + " tons"; 
   } 
} 
 
public class Cargo 
{ 
   public static int x = 0; 
   /** Weight of this cargo */ 
   private int weight; 
    
   /** Creates a piece of cargo with the given weight, in tons */ 
   public Cargo(int w) 
   { 
      this.weight = w; 
      Cargo.x += 10; 
   } 
    
   public int getWeight() 
   { 
      return this.weight; 
   } 
} 
Intro to Programming in Java        
600.107                 Johns Hopkins University 
 
 13 
Now suppose the following is in your main method. 
 
TradeShip s = new TradeShip();  
int cargo = 0; 
for (int i = 1; i < 6; i++) 
{ 
   Cargo goods = new Cargo(i); 
   cargo = s.addCargo(goods); 
} 
System.out.println(s.toString()); 
 
Trace the code, filling in the following table.  Place in each cell the value of the variable 
for that column at the BEGINNING of the iteration for that row (i.e. when the condition 
is checked).  Also place in the last row the output of the println statement.  Remember 
that an iteration is one complete run of the loop (checking the condition and 
running the code in the loop block), not just checking the condition.  Each cell should 
have a value.  There is no 0th iteration, iteration 1 is the first run of the loop. 
 
Iteration # i cargo (in main method) 
weight        
(in TradeShip 
instance s) 
cargo           
(in TradeShip 
instance s) 
Cargo.x 
1      
2      
3      
4      
5      
Printout at 
End  
 
 
 
 
 
 
 
 
 
 
 
Intro to Programming in Java        
600.107                 Johns Hopkins University 
 
 14 
V. Problem Code [16 pts] 
 
For each of the following code snippets there are multiple things wrong with the code, 
whether they be errors preventing the code from compiling or errors preventing it from 
doing what is desired.  Identify the errors and state how they would be corrected. 
 
1. [8 pts] In the following code, Spacecraft is a class which has a method warp().  Classes 
Rocket and Starship are both direct subclasses of Spacecraft and they both override the 
warp() method.  The code is supposed to create an array of length 5 of both Rockets and 
Starships, with Rockets at every even index (0 is considered even) and Starships at every 
odd index.  It is also supposed to print them out, using their toString() implementations.  
There is never more than 1 error in a single line.  There are no errors in lines 12 – 15. 
 
1.  Rocket&&Starship[] ships = new Spacecraft[5]; 
2.  for (int i = 0; i < ships.length; i++) 
3.  { 
4.     if (i % 2 == 0) 
5.        ships[i] = new Spacecraft(); 
6.     else 
7.        ships[i] = new Starship(); 
8.  } 
9.  for (int i = 0; i <= ships.length; i++) 
10.    System.out.println(ships[i].toString()); 
11.     
12. Spacecraft a = ships[0]; 
13. Spacecraft b = ships[1]; 
14. a = b; 
15. a.warp(); 
 
There are three errors in this code.  Identify them and say how they can be fixed. 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
If all the errors are fixed, which class’ warp() method is called in line 15?  Spacecraft’s, 
Starship’s, Rocket’s, or some default implementation inherited from Object? 
Intro to Programming in Java        
600.107                 Johns Hopkins University 
 
 15 
2. [8 pts] There is an interface Packable.  Assume Item is some pre-defined class. 
 
public interface Packable 
{ 
   public boolean addItem(Item x); 
   public Item removeItem(Item x); 
} 
 
The following class is supposed to be a subclass of some pre-defined class Bag, and 
implement the Packable interface.  The … in line 17 is not an error, it just indicates 
some irrelevant code goes there that is not shown. 
 
1.  public class Backpack inherits Bag implements Packable 
2.  { 
3.     int maxItems; 
4.     int num; 
5.      
6.     public Backpack(int capacity) 
7.     { 
8.        this.maxItems = capacity; 
8.        this.num = 0; 
10.    } 
11.     
12.    public boolean addItem(Item x, int index) 
13.    { 
14.       if (this.num < this.capacity)  
15.       { 
16.          // Add the item somehow 
17.          ... 
18.          this.num++; 
19.   return true; 
20.       } 
21.       return false; 
22.    } 
23. } 
 
There are four errors in this code (only in Backpack, none in Packable).  Identify 
them and say how they can be fixed. 
 
 
 
 
 
 
 
 
 
 
 
 
 
Intro to Programming in Java        
600.107                 Johns Hopkins University 
 
 16 
VI. Writing Code [16 pts] 
 
Mario gets a tip from Luigi that Peach is stuck in one of those green pipes.  Write a 
recursive method that Mario can use to find which pipe she is stuck in.  Use the following 
class to represent a pipe. 
 
public class Pipe 
{ 
   private Pipe left; 
   private Pipe right; 
   /** positive unique identifier, different than any other Pipe */ 
   private int uid; 
   /** true if Peach is stuck in this Pipe, false if not; will be 
    * true in only 1 Pipe in the system */ 
   private boolean peachStuckHere; 
    
   public Pipe getLeft() 
   { 
      return this.left; 
   } 
    
   public Pipe getRight() 
   { 
      return this.right; 
   } 
    
   public int getUid() 
   { 
      return this.uid; 
   } 
    
   public boolean isPeachHere() 
   { 
      return this.peachStuckHere; 
   } 
 
   ... 
 
} 
 
This class has a constructor, and other methods, but they are unimportant because all 
you’ll need to access are the public getters.  Your method must take as input a Pipe 
variable and return an integer, which is the uid of the Pipe Peach is stuck in.  You can 
assume all the variables will have actual values (or possibly be null in the case of left and 
right).  If both left and right are null, then that’s a dead-end.  They will either both be 
null, or both refer to other Pipes, never will only 1 be null.  It is possible that Peach is not 
in the pipe system (Luigi could be lying because he always did like Peach…), in which 
case you should return -1.  Make sure to properly Javadoc your method. 
 
 
 
 
 
Intro to Programming in Java        
600.107                 Johns Hopkins University 
 
 17