Assignment 7, due Oct 13

Solutions

Part of the homework for CS:2820, Fall 2017
by Douglas W. Jones
THE UNIVERSITY OF IOWA Department of Computer Science

  1. Background: The following have to do with problems some students had on the exam.

    a) If a is an array, you can write a[i] to select the ith element of the array. How do you select the ith element of the list x? (0.5 points)

    This works for all implementations of the interface List: x.get(i)

    b) When you type the shell command java Roadnetwork 2>somefile what does the 2>somefile at the end of the command do? (0.5 points)

    It redirects standard error to somefile.

    The above is a sufficient answer, but the following may be helpful: By default, standard error goes to the terminal. The previous contents (if any) of somefile will be overwritten. If the file somefile did not exist, it will be created. In a Java program, standard error is visible as System.error.

  2. Background: Look at the code at the end of Lecture 14 from Oct. 10. There is a lambda expression in the initializer for the static variable eventSet.

    A question: What is that lambda expression used for? (0.5 points)

    It defines the Comparator used by the PriorityQueue that implements the eventSet; this determines how events are sorted into order.

  3. Background: At the end of Lecture 14 from Oct. 10., two simulation frameworks were given.

    a) Write code to schedule a call to System.exit(0) at time 100.00 using the first framework. (0.5 points)

    A short answer:

    schedule( new Simulator.event {
        time = 100.00f;
        void trigger() {
            System.exit( 0 );
        }
    } );
    

    The above uses an anonymous instance of an anonymous subclass, the following longer code may be easier to understand with an explicit but very local inner subclass:

    {
        class ExitEvent extends Simulator.event {
            ExitEvent() {
                time = 100.00f;
            }
            void trigger() {
                System.exit( 0 );
            }
        }
        Simulator.schedule( new ExitEvent() );
    }
    

    b) Write code to schedule a call to System.exit(0) at time 100.00 using the second framework. (0.5 points)

    The following is the form of call to schedule you'd use following the instructions in the comments on the declaration of schedule.

    Simulator.schedule( 100.00f, (float time)->System.exit( 0 ) );
    

    c) Rewrite the code from part b without using lambda notation, anonymous subclasses or anonymous variables. (0.5 points)

    The following answer would be an acceptable answer to both parts b and c, but it's harder code to write, but perhaps easier to understand.

    {
        class ExitEvent implements Simulator.action {
            void trigger( float time ) {
                System.exit( 0 );
            }
        }
        new exitEvent = ExitEvent();
        Simulator.schedule( 100.00f, exitEvent() );
    }