CS 145 Lecture 10 – Midterm 1 review
Things to know
- The test is hand-written.
- You may write SOP instead of System.out.println.
- You need not import any classes.
- The front page of the exam will contain compact documentation for the Scanner, Random, and String classes.
- A strategy: on questions where you are asked to write a method, write the method signature first, not worrying about what it’s supposed to do. Just get the return type and arguments framed correctly. Then read what the method is supposed to do and implement it.
Review questions
- What is printed to System.out when the following code is run? Assume double arithmetic does not result in a loss of precision. If a double is printed, include a decimal point in your output.
String numbers = "123456789"; int unlucky = 13; double cents = 25.0; System.out.println(numbers.charAt(1)); System.out.println(numbers.length()); System.out.println(((double) numbers.length() + 1) / 4); System.out.println(unlucky / 2); System.out.println(unlucky % 10); System.out.println(cents * 2); System.out.println(cents / 2); System.out.println((cents - unlucky) / 2); System.out.println("(int) 13.9");
- Assume the following declarations and assignments:
double d1 = 5.0; double d2 = 4.0; int i1 = 10; int i2 = 10; int i3 = 3; char c1 = '1'; String s = "abcd123";
Given these variables, what are the types and values of the following expressions?
d2 < d1 d1 == d2 ((double) s.length()) / 2 s.substring(0, 3) + s.charAt(3) i2 / i3 * i3 i1 >= i2 && i2 >= i3 "34" + i2 + c1 i2 + 200 + "34" s.substring(4).length() != 0 d1 - i2 / i3
- What is printed by the following loop? Write the output as it would appear on the
console.String name = "fgirgouurned"; System.out.println(name.length()); for (int i = 1; i < name.length(); i = i + 2) { System.out.println(name.charAt(i) + "-" + i); }
- Write a method reverse that takes a String argument and returns the String reversed.
- Suppose you’ve got two Scanners:
Scanner inA = new Scanner(...); Scanner inB = new Scanner(...);
Compare the two input streams token by token. (Recall, a token is delimited chunk of text.) Where the tokens differ, print a String of the form “tokenA != tokenB” (where tokenA is replaced by the token from inA and tokenB by the token from inB). You may assume the two input streams have the same number of tokens.
- Write code to print out n random ints in the range [0, 100].