CS 145 Lecture 27 – Final review
May 11, 2012 by Chris Johnson. Filed under cs145, lectures, spring 2012.
Agenda
- our own String class
- indexOf
- replace
- startsWith
- concat
- a 2-D ripple
- a bus counter
- Bingo board
Code
MyString.java
package prefinal;
public class MyString {
private char[] charries;
public MyString(char[] src) {
charries = src;
}
/**
* Gets the index of first instance of the
* specified character. If character cannot
* be found, -1 is returned.
*/
public int indexOf(char c) {
for (int i = 0; i < charries.length; ++i) {
if (charries[i] == c) {
return i;
}
}
return -1;
}
public int lastIndexOf(char c) {
for (int i = charries.length - 1; i >= 0; --i) {
if (charries[i] == c) {
return i;
}
}
return -1;
}
public int length() {
return charries.length;
}
public char charAt(int i) {
return charries[i];
}
public boolean startsWith(MyString prefix) {
// This string isn't long enough to even contain prefix.
// Oh my goodness! Let's get outta here.
if (prefix.length() > length()) {
return false;
}
for (int i = 0; i < prefix.length(); ++i) {
if (prefix.charAt(i) != charAt(i)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
MyString stuff = new MyString("The quick brown fox jumped over the lazy dog".toCharArray());
System.out.println(stuff.indexOf('T'));
System.out.println(stuff.indexOf('q'));
System.out.println(stuff.indexOf('z'));
System.out.println(stuff.indexOf('3'));
System.out.println(stuff.lastIndexOf('.'));
System.out.println(stuff.lastIndexOf('u'));
System.out.println(stuff.startsWith(new MyString("Bless you".toCharArray())));
System.out.println(stuff.startsWith(new MyString("".toCharArray())));
}
}
Ripple.java
package prefinal;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class Ripple {
public static void main(String[] args) throws FileNotFoundException {
double[][] heights = new double[100][100];
for (int r = 0; r < heights.length; ++r) {
for (int c = 0; c < heights[r].length; ++c) {
int diffX = c - heights[r].length / 2;
int diffY = r - heights.length / 2;
double distance = Math.sqrt(diffX * diffX + diffY * diffY);
heights[r][c] = Math.sin(distance);
}
}
PrintWriter out = new PrintWriter("/home/user/Desktop/heights.txt");
for (int r = 0; r < heights.length; ++r) {
for (int c = 0; c < heights[r].length; ++c) {
out.print(heights[r][c] + " ");
}
out.println();
}
out.close();
}
}
Haiku
You’ve seen all the tricks.
There’s no magic in software.
Just lots of hard fun.
show