// this is a txt file because Splash won't let me upload a .java // file so rename it -- jaz /* * A primitive number class which supports addition and * subtraction of nonnegative integers and also * the ability to create a loop that "counts" as many * times as the integer represents. */ public class Number implements Comparable { public class Stone { public final Stone next; public Stone( Stone next ) { this.next = next; } } private Stone first; // the first Stone in a list of stones // is null iff list is empty private Stone theCursor; // for looping through a number without // changing it public Number() { this.theCursor = null; this.first = null; } public Number clone() { Number n = new Number(); while( count() ) { n.addOne(); } return n; } public boolean isZero() { return first==null; } public Number addOne() { first = new Stone(first); return this; } public Number subOne() { if( !isZero() ) { first = first.next; } return this; } public Number add( Number n ) { while( n.count() ) { addOne(); } return this; } public Number sub( Number n ) { while( n.count() ) { subOne(); } return this; } public int compareTo( Number x ) { while( count() & x.count() ) { } // note & instead of && to avoid shortcutting int retval = 0; // remains 0 if both counts are finished if( cursor()!=null ) { // haven't finished counting // this if and the if below cannot both evaluate to true while( count() ) { } retval = -1; } if( x.cursor()!=null ) { while( x.count() ) { } retval = 1; } return retval; } /// for looping through a Number without changing it /// /// we are "between counts" when cursor is null public boolean count() { if( theCursor==null ) { theCursor = first; } else { theCursor = theCursor.next; } return theCursor!=null; } public Stone cursor() { return theCursor; } /// conversions /// public String toString() { theCursor = null; String s = ""; while( count() ) { s+="I"; } return s; } private static int size ( Number n ) { Stone s = n.first; int i = 0; while( s!=null ) { i += 1; s = s.next; } return i; } public static Number fromDecimal( int n ) { Number retval = new Number(); for( int i=0; i