interface TVI { final int DEFAULT_MAX = 99; int getCurrentChannel(); void incChannel (); void decChannel (); void alternateChannel (); }
Solution
class TV implements TVI { int maxChannels; int currentChannel; int previousChannel; TV () { this(DEFAULT_MAX); } TV (int m) { maxChannels = m; currentChannel=1; previousChannel=1; } public int getCurrentChannel () { return currentChannel; } public void incChannel () { previousChannel = currentChannel; currentChannel++; if (currentChannel > maxChannels) currentChannel=1; } public void decChannel () { previousChannel = currentChannel; currentChannel--; if (currentChannel < 1) currentChannel=maxChannels; } public void alternateChannel () { int temp; temp = currentChannel; currentChannel = previousChannel; previousChannel = temp; } }
int numberOfLines (StreamTokenizer st) throws java.io.IOException;that reads tokens from the StreamTokenizer object st until the end of the stream, and returns a count of the number of lines it encountered. You may assume that the object st treats ends of line as tokens (see the method eolIsSignificant in the API).
Solution
int numberOfLines (StreamTokenizer st) throws java.io.IOException { int count = 0; while (st.nextToken() != st.TT_EOF) { if (st.ttype == st.TT_EOL) count++; } return count; }
Solution
abstract class Appliance { abstract void accept (Command c); abstract void turnYourselfOff(); } class TV extends Appliance { void accept (Command c) { c.forTV(this); } void incChannel () { previousChannel = currentChannel; currentChannel++; if (currentChannel > maxChannels) currentChannel=1; } void turnYourselfOff() { ... } } class Fridge extends Appliance { void accept (Command c) { c.forFridge(this); } void turnYourselfOff() { ... } } interface Command { void forTV (TV a); void forFridge (Fridge a); } class OffCommand extends Command { void forTV (TV a) { a.turnYourselfOff(); } void forFridge (Fridge a) { a.turnYourselfOff(); } } class ChangeChannel extends Command { void forTV (TV a) { a.incChannel(); } void forFridge (Fridge a) { /* ignore */ } }
sabry@cs.uoregon.edu