...Problem Set 1
-
Create an interface to describe a warship in the game
"Battleship". The interface should include the following:
method | arguments | return type |
length | none | int |
orientation | none | 1=North, 2=East, 3=West, 4=South |
name | none | String |
take damage | int | void |
-
Create five implementations of the battleship above.
-
Consider the following abstract class:
Builder.java |
1 | public abstract class Builder { |
2 | // Appends just one character |
3 | public abstract void append(char c); |
4 | |
5 | // Force implementer to create a toString method. |
6 | public abstract String toString(); |
7 | |
8 | // Makes use of the append(char) method |
9 | // to append a whole string. |
10 | public void append(String s) { |
11 | for(int i=0;i<s.length();i++) { |
12 | append(s.charAt(i)); |
13 | } |
14 | } |
15 | |
16 | // Makes use of the fact that all Objects |
17 | // have a toString() method to format all |
18 | // other objects. |
19 | public void append(Object o) { |
20 | if(o == null) |
21 | append("null"); |
22 | else |
23 | append(o.toString()); |
24 | } |
25 | } |
$ javac Builder.java
|
and the following implementation:
CapBuilder.java |
1 | public class CapBuilder extends Builder { |
2 | StringBuffer sb = new StringBuffer(); |
3 | public void append(char c) { |
4 | sb.append(Character.toUpperCase(c)); |
5 | } |
6 | public String toString() { |
7 | return sb.toString(); |
8 | } |
9 | public static void main(String[] args) { |
10 | CapBuilder cb = new CapBuilder(); |
11 | cb.append("Hello, world."); |
12 | System.out.println(cb); |
13 | } |
14 | } |
$ javac CapBuilder.java
| $ java CapBuilder
HELLO, WORLD.
|
We want to create a new Builder, NumBuilder, that converts digits to
words, i.e. the string "1, 2, and 3." becomes "One, Two and Three."
The string "10" becomes "OneZero".
Most of the method is given to you, just fill in the append method.
You may not use a loop construct ("for" or "while").
NumBuilder.java |
1 | public class NumBuilder extends Builder { |
2 | StringBuffer sb = new StringBuffer(); |
3 | public void append(char c) { |
4 | // What goes here? |
5 | } |
6 | public String toString() { |
7 | return sb.toString(); |
8 | } |
9 | public static void main(String[] args) { |
10 | NumBuilder nb = new NumBuilder(); |
11 | nb.append("1, 2, and 3."); |
12 | System.out.println(nb); |
13 | nb.append("4 and 5"); |
14 | } |
15 | } |
$ javac NumBuilder.java
|
- Write a program to find the first 10 prime numbers, i.e. integers that are
only evenly divisible by themselves and 1. Hint: Make a big array of booleans
named "isprime" and mark off all the non-prime numbers as false,
i.e. isprime[4] = false.
|