Download Sample CS112 Exam 1

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Sample CS112 Exam 1
YOUR NET ID ______________________________________
YOUR NAME ________________________________________
TODAY'S DATE _____________________________________
GENERAL INSTRUCTIONS
Answer each of the questions below. Write your answers directly on the examination paper,
including any work that you wish to be considered for partial credit.
Each question is marked with the number of points assigned to that problem. The total number
of points is 50, and accounts for 1.5 psets. We design the exam for 75 minutes (11:35-12:50
pm) and intend that the number of points be roughly comparable to the number of minutes you
should spend on that problem. Since the problems are not ordered according to difficulty, you
may want to first look at all the problems and schedule your time accordingly.
Unless otherwise indicated as part of the instructions for a specific problem, comments will
not be required on the exam. Uncommented code that gets the job done will be sufficient for
full credit on the problem. On the other hand, comments may help you to get partial credit on a
problem if they help us determine what you are trying to do.
The examination is close-book, no computers, but you can bring a one-page summary.
1/9
YOUR GRADE
PROBLEM 1 (25 points):
____________________
PROBLEM 2 (10 points):
____________________
PROBLEM 2 (15 points):
____________________
TOTAL
Bonus
(50 points):
____________________
(5 points):
____________________
2/9
Problem 1. Short Questions (25 points)
1.a. [Arithmetic Expression; 5 pts]: What will be printed by the println statement below?
You can get partial credit by writing out intermediate steps.
System.out.println( 2016 / 100 * 100 + 2016 % 100 + “ == ” + 2016 );
1b. [Boolean Expression, Char; 4 pts] Which one of the following conditions does not test
whether char ch is a lower-case letter (i.e., a char between ‘a’ and ‘z’, inclusive)?
A.
B.
C.
’a’ <= ch && ch <= ‘z’
!(’a’ > ch || ch > ‘z’)
’a’ <= ch || ch <= ‘z’
1c. [Variable Definition; 3 pts] Which one of the following correctly defines a class-scope
double constant?
A) final double NICKEL_VALUE == 0.05;
B) double NICKEL_VALUE = 0.05;
C) static final double LITERS_PER_GALLON = 3.875;
D) static final double LITERS_PER_GALLON == 3.785;
3/9
1d. [Mixed Types; 3 pts]: The program segment below tries to extract the cents from a double
storing the total balance in dollars. The compiler will complain about the second line if without
the (int). What is the problem?
double balance
= 3.16;
int
balanceInt = (int)Math.round(balance * 100);
int
cents
= balanceInt % 100; // cents should be 16
1e. [Conditional Statement Using Nested if/else; 5 pts] Please fill in the blanks so that the
System.out.println statement prints out face = 0 with 10% probability, face = 1 20%, and face =
2 the remaining.
for (int i = 0; i < 1000; i++) {
double r = Math.random(); // random number in [0.0, 1.0)
int face;
if (r < 0.1)
face = 0;
else if (r < ________)
face = ______;
else
face = 2;
System.out.println(“face = “ + face);
} // end of for loop
1f. [Method Overloading, Method Parameter Passing, and printf; 5 pts] What will be printed by
the following program:
public class ParameterMystery {
public static void main(String[] args) {
int x = 1;
int y = 2;
int z = 3;
mystery(z, y, x + 0.0);
}
public static void mystery(int x, int y,
System.out.printf( “1: %d and %d“,
}
public static void mystery(int x, int y,
System.out.printf( “2: %.2f and %d“,
}
int z) {
z, (y - x) );
double z) {
z, (y - x) );
}
4/9
Problem 2. Writing Methods (10 points)
2a. [String Manipulation; 5 pts]: A common operation in a shipping app (e.g., by USPS,
FedEx, UPS) is to extract the zip code from an address string. Assume that the address string is
a string containing city name, “,”, two-letter state abbreviation and then 5-digit zip code, e.g.,
String addr = “New Haven, CT 06511”;
Write a method to extract the zip code from an address string and return it to as an integer:
public static int getZipcode(String addr) {
// fill in method body below
} // end of method
2b. [Boolean Method Definition; 5 pts] Please complete the following method (both the
signature and the body) so that the method returns a predicted integer grade according to the
following rule: A student will get 100 on an exam if she is a genius or she has studied for the
exam; otherwise, she receives 80.
public static _________ predictGrade(boolean genius, boolean hasStudied) {
// fill in method body below
} // end of method
5/9
Problem 3. Reading and Finishing a Complex Program (15 points)
A Yale graduate student made headlines recently by writing a program to analyze movie
reviews to predict Oscar Awards. The basic idea of such a program can be simple. It partitions
words into categories (e.g., bad or good), and then scans the reviews to count the number of
words in each category. Below is a program that scans a file containing all reviews for a movie,
counts the words in two categories, and then displays a bar chart of the counters.
1.
2.
3.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
4.
5.
6.
7.
8.
public class ReviewAnalyzer {
static int nGood, nBad;
// counters of words in two categories
// Words in each category; a real program will have a longer list
final static String[] badWords = {"bad", "mediocre", "horrible", "terrible"};
final static String[] goodWords = {"good", "excellent", “brilliant”, "wonderful"};
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
public static void main(String[] args) _____________ {
Scanner console = new Scanner(System.in);
System.out.print("Review file: ");
String fileName = console.nextLine();
Scanner input = new Scanner(new File(fileName));
// (3.a)
// (3.b)
analyze(input);
display();
console.close();
} // end of main
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
// Scan each word in the file pointed out by input
public static void analyze(Scanner input) {
nGood = 0; nBad = 0;
while ( _______________ ) {
String word = input.next();
if ( contains(word, badWords) )
nBad ++;
else if ( contains(word, goodWords) )
nGood ++;
} // end of while
} // end of analyze
29.
30.
31.
32.
33.
34.
35.
36.
// Check if word is in wordList
public static boolean contains(String word, String[] wordList) {
for (int i = 0; i < wordList.length; i++) {
if ( word.equals( wordList[i] ) )
return true;
}
return false;
} // end of contains
37.
38.
39.
40.
41.
42.
// Display the two counters as two bars
public static void display() {
StdDraw.setXscale(0, 2);
int yScale = ______; // y axis range: larger of nGood/nBad
StdDraw.setYscale(0, yScale);
StdDraw.line(0, 0, 2, 0); // draw base line
// (3.c)
// (3.d)
// (3.e)
43.
44.
StdDraw.text(
0.5, nBad/2.0, "Bad:"+nBad);
// text and bar for bad
StdDraw.rectangle(0.5, nBad/2.0, 0.25, nBad/2.0); // bar height: nBad
45.
46.
StdDraw.text(
1.5, nGood/2.0, "Good:"+nGood); // text and bar for good
StdDraw.rectangle(1.5, nGood/2.0, 0.25, nGood/2.0); //bar height: nGood
47.
48.
} // end of method display
} // end of class ReviewAnalyzer
6/9
3.a. [3 pts] Why does the program need the statement at line 1?
3.b. [3 pts] The compiler will complain about exception at line 13. Add what is missing at line
9 so that the program will compile.
3.c. [3 pts] The analyze method scans each word. Add the condition for the while loop at
line 21 so that it can examine each word in the review file and update the counters.
3.d. [3 pts] Someone claims that the condition at line 32 should be word
you agree or not?
== wordList[i].
Do
3.e. [3 pts] To generate the example chart such as shown on
the right, which is for a file containing “terrible some part is
good the performance is definitely excellent brilliant and
wonderful”. What is a reasonable expression to set the y scale
at line 40?
7/9
Bonus [5 pts]. You can do at most one bonus.
Please check which one we should grade: Bonus.a: ____
Bonus.b: _____
[Bonus.a] A perfect number n is a positive number that is equal to the sum of its proper
positive divisors, where a number k is a proper positive divisor of n if k is smaller than n and n
is divisible by k. For example, 6 is a perfect number because 6 = 1 + 2 + 3; 28 is a perfect
number because 28 = 1 + 2 + 4 + 7 + 14; however, -6 is not a perfect number because it is not
positive; 1 is not a perfect number; neither is 4 a perfect number because 4 != 1 + 2. Although
the study of perfect numbers started in early Greek mathematics, computing such numbers
manually is hard. It took until 1588 AD for the Italian mathematician Pietro Cataldi to discover
the sixth (8,589,869,056) and the seventh (37,438,691,328) perfect numbers.
Write a complete static method isPerfect(long n) that takes an arbitrary integer n and
returns true if n is a perfect number and false otherwise. Hint: cumulative sum loop.
public static boolean isPerfect(long n)
{
}
8/9
[Bonus.b] Please write a method with parameter n (1 <= n <= 9) to print out a number pattern
with n rows. The first row has n, next row n and n-1, etc. For example, for n = 9, the method
prints:
9
98
987
9876
98765
987654
9876543
98765432
987654321
public static void printPattern(int n)
{
}
9/9