Solutions to exciting final practice problems
Problem A
// Indexing is much easier going from back to front
public static void deleteSevens(ArrayList<Integer> alist) {
for (int i = alist.size()-1; i >= 0; i--) {
if (alist.get(i) % 7 == 0 || contains7v2(alist.get(i))) {
alist.remove(i);
}
}
}
// One way of writing contains7 is to use Strings and concatenation...
public static boolean contains7(int n) {
return ("" + n).contains("7");
}
// Another way is to use integer division and modular arithmetic
public static boolean contains7v2(int n) {
while (n > 0) {
if (n % 10 == 7) {
return true;
} else {
n /= 10;
}
}
return false;
}
public static void main(String[] args) {
ArrayList<Integer> alist = new ArrayList<Integer>();
for (int i = 0; i < 100; i++) {
alist.add(i+1);
}
deleteSevens(alist);
System.out.println(alist);
}
Problem B
public static String[] prepend(String[] strings, String prefix) {
String[] strs = new String[strings.length];
for (int i = 0; i < strs.length; i++) {
strs[i] = prefix + strings[i];
}
return strs;
}
Problem C
public class Rectangle {
private double left;
private double top;
private double width;
private double height;
public Rectangle(double left, double top, double width, double height) {
this.left = left;
this.top = top;
this.width = width;
this.height = height;
}
public double getLeft() { return left; }
public double getTop() { return top; }
public double getWidth() { return width; }
public double getHeight() { return height; }
public double area() { return width * height; }
public double perimeter() { return 2 * width + 2 * height; }
public double diagonal() {
return Math.sqrt(width * width + height * height);
}
public String toString() {
return "{ " + getLeft() + ", " + getTop() + ", " +
getWidth() + ", " + getHeight() + " }";
}
}