Spring 2004, Midterm 1 suggested solutions. On question 1 I also list the concept being tested. (ignore differences in spacing, capitilizaition) 1. Answer as written or -2 A. Order of operations, variables 25 B. implict casting, mixed mnode arithmetic 2.5 C. arrays, array initialization, length field 9 D. for loops 40 E. Strings, calling methods, for loops cte F. behavior of value parameters, primitive parameters 12 39 12 39 G. behavior of value parameters, pointers as value parameters Brown Brown blue blue H. behavior of value parameters, pointers as value parameters Brown Brown Brown Brown I. == and pointers false J. accessing private data members (made a mistake on identifier) syntax error. hair not defined or hair has private access K. pointers and sharing pointees grey grey grey grey L. inheritance of methods, abstract methods 24 3D Shape M. polymorphism of variables 6 1 3D Shape N. interfaces syntax error 0. 2d arrays 8 4 2. most common errors were: confusing the number of outcomes with the outcomes not checking for outliers on both ends not using numEvents for the maximum number of outliers (to avoid constant resize) public int[] outliers() { double outRange = 3 * standardDeviation(); double mean = mean(); int[] results = new int[numEvents()]; double low = mean - outRange; double high = mean + outRange; int numOutliers = 0; for(int i = 0; i < myData.length; i++) { if( myData[i] > 0 && (i < low || i > high) ) { for(int j = 0; j < myData[i]; j++ ) { results[numOutliers] = i; numOutliers++; } } } return resize(results, numOutliers); } 3. most common errors were: failure to reset counter of number of 0s not checking for new max at the end of a row counting total number of 0s in row instead of streaks not resetting run length if not a new max public int maxUntargetedLength(int[][] grid) { int maxRow = -1; int runLength = 0; int maxRun = 0; for(int r = 0; r < grid.length; r++) { runLength = 0; for(int c = 0; c < grid[0].length; c=+) { if( grid[r][c] == 0) { runLength++; } else { if(runLength > maxRun) { maxRun = runLength; maxRow = r; } runLength = 0; } } // was streak at end of row a new max? if(runLength > maxRun) { maxRun = runLength; maxRow = r; } } return maxRow; } 4. most common errors: logic error in isOddLot not casting parameter of equals method to a Bid using == instead of .equals to check equality of Strings public class Bid { private String myTicker; private double myPrice; private int myNumShares; public Bid(String ticker, double price, int numShares) { //pre: for a market order price = -1 myTicker = ticker; myPrice = price; myNumShares = numShares; } public boolean isOddLot() { return myNumShares % 100 != 0; } public double price() { return myPrice; } public String ticker() { return myTicker; } public boolean equals(Object other) { Bid otherBid = (Bid)other; return myTicker.equals(otherBid.myTicker) && myPrice == otherBid.myPrice && myNumShares == other.myNumShares; } }