Download Midterm Review: Karel and Java Programming Practice Problems and more Exams Java Programming in PDF only on Docsity!
Midterm Review
Eric Roberts
CS 106A
February 8, 2016
/*
- File: BreakoutKarel.java
- The BreakoutKarel class solves the Karel problem from the
- first practice midterm exam. / import stanford.karel.; public class BreakoutKarel extends SuperKarel { public void run() { while (beepersInBag()) { if (beepersPresent()) { pickBeeper(); bounce(); } while (frontIsBlocked()) { bounce(); } stepDiagonally(); } } /*
- Causes Karel to perform a ricochet bounce, which requires
- no more than turning left. / private void bounce() { turnLeft(); } /
- Step diagonally. The precondition for this call is that
- Karel's front must be clear. The postcondition has Karel
- facing in the same direction. */ private void stepDiagonally() { move(); if (leftIsClear() && noBeepersPresent()) { turnLeft(); move(); turnRight(); } } }
Karel Plays Breakout
page 2 of 2
Karel—Practice
99 1044 97 1011
The outer loop cycles through each corner on 1
st
Street
calling checkTemperature at every position.
When Karel reaches a beeper pile, it tries to take 100
beepers away.
If the beeper pile is empty after the loop, the patient’s
temperature is in the allowable range, and Karel can
simply empty its bag to restore the beeper pile.
If the beeper pile after taking 100 beepers away still
contains beepers, the temperature is high. In that case,
Karel paints the current corner red and reconstructs
the original beeper pile.
The same process continues at every corner up to the
end of 1
st
Street.
/*
- File: KarelCare
- Karel looks through the hospital ward for patients with
- temperatures over 100 and paints the square under the
- temperature red so that doctors can treat the patient. / import stanford.karel.; public public class KarelCare extends SuperKarel { public void run() { while (frontIsClear()) { if (beepersPresent()) { checkTemperature(); } move(); } if (beepersPresent()) { checkTemperature(); } } /* Flags temperatures greater than 100 */ private void checkTemperature() { for (int i = 0; i < 100; i++) { if (beepersPresent()) { pickBeeper(); } } if (beepersPresent()) { paintCorner(RED); } while (beepersInBag()) { putBeeper(); } } }
KarelCare
page 2 of 2
Expression Tracing—Practice
false
false
"B" + 8 + 4
"B8"
"B84"
Both of these operands are integers so the result is truncated to an int_. Because the left operand of the_ && operator is false , Java does not evaluate the right operand, thereby avoiding the division-by-zero error.
Algorithmic Tracing—Practice
private String mystery(String s) { String result = ""; int len = s.length(); int j = 0; int k = 9; while (j < k) { if (j < 4) { result += s.charAt(k % len); } if (j / 2 != 1) { result += s.charAt(j % len); } j++; k--; } return result; } len str "abcdefg" j k result 7 012345 987654 "cabbage""cabbag""cabba""cabb""cab""ca""c" ""
Algorithmic Tracing—Practice
private int mystery(int n) { while (n >= 10) { int k = 0; while (n > 0) { k += n % 10; n /= 10; } n = k; } return n; } n 1729 k 11181910090901 1721719101010101
Method Tracing—Practice
public void run() { String s1 = "Heart"; String s2 = valentine("candy", s1); println("s1 = " + s1); println("s2 = " + s2); } Problem2c s1 = Heart s "earth" s "Heart" s2 = earth private String valentine(String s1, String s2) { int num = (s1.substring(1, 2)).length(); s1 = s2.substring(num); s2 = cupid(s1, s2.charAt(0)); return (s2); } num s "Heart" s 1 "candy""eart" "earth" private String cupid(String s1, char ch) { return (s1 + Character.toLowerCase(ch)); } s1 ch "eart" 'H'
Problem 3—Practice
In Assignment # 2 , you wrote a program to find the largest and
smallest integers in a list entered by the user. For this problem,
write a similar program that instead finds the largest and the
second-largest integer. As in the homework problem, you should
use 0 as a sentinel to indicate the end of the input list. Thus, a
sample run of the program might look like this:
FindTwoLargest This program finds the two largest integers in a list. Enter values, one per line, using a 0 to signal the end of the list. ? 17 ? 42 ? 11 ? 19 ? 35 ? 0 The largest value is 42 The second largest value is 35
Problem 3—Practice
As you undoubtedly learned in school, the Pythagorean Theorem
holds that the length of the hypotenuse ( z ) of a right triangle with
sides x and y is given by the following formula:
x
2
+ y
2
= z
2
Write a Java program that prints out all Pythagorean triples in
which both x and y are less than or equal to a named constant MAX
and x is less than y For example, if MAX is 25 , your program
should generate the following sample run:
PythagoreanTriples 3, 4, 5 5, 12, 13 6, 8, 10 7, 24, 25 8, 15, 17 9, 12, 15 10, 24, 26 12, 16, 20 15, 20, 25 18, 24, 30 20, 21, 29
import acm.program.; import acm.graphics.; public class PythagoreanTriples extends ConsoleProgram { public void run() { for (int a = 1; a <= MAX; a++) { for (int b = a; b <= MAX; b++) { int csq = a * a + b * b; int c = GMath.round(Math.sqrt(csq)); if (c * c == csq) { println(a + ", " + b + ", " + c); } } } } /* Maximum value for a and b */ private static final int MAX = 25; }
Finding Pythagorean Triples
/*
- File: RandomlyMovingRedCross.java
- This program solves the practice midterm problem. / import acm.program.; import acm.util.; import java.awt.event.; public class RandomlyMovingRedCross extends GraphicsProgram { /* Sets up the program at the beginning */ public void init() { cross = new RedCross(); add(cross, getWidth() / 2, getHeight() / 2); chooseRandomDirection(); addMouseListeners(); }
Red Cross
page 1 of 4
/*
- File: RandomlyMovingRedCross.java
- This program solves the practice midterm problem. / import acm.program.; import acm.util.; import java.awt.event.; public class RandomlyMovingRedCross extends GraphicsProgram { /* Sets up the program at the beginning / public void init() { cross = new RedCross(); add(cross, getWidth() / 2, getHeight() / 2); chooseRandomDirection(); addMouseListeners(); } / Runs the simulation / public void run() { while (true) { cross.movePolar(VELOCITY, direction); pause(PAUSE_TIME); } } / Called when the mouse is clicked / public void mouseClicked(MouseEvent e) { if (cross.contains(e.getX(), e.getY())) { chooseRandomDirection(); } } / Resets the direction to a random value */ private void chooseRandomDirection() { direction = rgen.nextDouble(0, 360); }
Red Cross
page 2 of 4