/* A first "interesting" Espresso program * by CMB 8/04 * * This is a program that builds a list and prints it out. Then it * modifies the list, and prints part of it again. It does not test * all of the features of Espresso. * * It uses class IntList, which in turn uses class IntNode. It's a * somewhat realistic program: there are only a few places where we * have done weird stuff to illustrate language features. * * Comments strewn throughout the program mention restrictions on Espresso * that aren't in Java and other language features being used. */ /* * NOTE: In Espresso all methods have return values. Many of the * methods here use the convention of returning the updated object as * the return value. This allows a style where method calls may be * strung together. See the example of this in class IntList, method * buildAList */ // the main class is only allowed to have one method. class ListProg { public static void main (String[] args) { IntList myList; // no initializers allowed myList = new IntList(); myList.buildAList(); myList.printList(); System.out.println(); myList.insertVal(3); myList.insertVal(5); myList.printList(); // test early return on 3: should print 5 only // no return on main } } class IntList { IntNode head; // inserts i into front of list IntList insertVal(int i) { IntNode newNode; newNode = new IntNode(); newNode.init(i); if (head == null) { head = newNode; } else { newNode.setNext(head); head = newNode; } return this; // return the updated list } // builds the list (10 20 30 . . . 90 100) // from back to front int buildAList() { int i; // no initializers allowed i = 5; while (0 < i) { // no >; no for loops // add two vals in each iteration just to show // stringing together method calls // (of course, this is not the clearest way to write the code). // also method calls require "." form: so need explicit "this" this.insertVal(i*2*10).insertVal((i*2-1)*10); i = i - 1; // no ++ or -- } return 0; // dummy value. all methods have to return something } // Sometimes prints the whole list, // but stops early if it gets to a 3 in the list. // Why? So we can show the short-circuit && int printList() { IntNode p; p = head; while (p != null && p.getVal() != 3) { // short-circuit && System.out.println(p.getVal()); p = p.getNext(); } return 0; } } class IntNode { int data; IntNode next; IntNode init(int num) { data = num; next = null; // same as default value: but do this for clarity return this; } IntNode setNext(IntNode nextVal) { next = nextVal; return this; } IntNode getNext() { return next; } int getVal() { return data; } }