Assignment 10, due Apr 14Solutions
Part of
the homework for CS:2820, Spring 2017
|
On every assignment, write your name and section number. Write your name as it appears on your university ID card! Use the section number as it appears in your current registration! We will not do detective work to figure out who did what. Homework is due on paper at the start of your discussion section. Exceptions will be made only by advance arrangement with your TA (excepting "acts of God"). Never push homework under someone's door!
System.out.print( " " + g.name );
A problem: Write code to replace the above that pads shorter names to 5 characters and truncates longer names. This is a small exercise in Java string manipulation. Computational efficiency is not really important, as this code is only used once to compute the title line of the output. Hint: It can be done in one simple expression involving concatenation and substring operations. (1 point)
System.out.print( " " + g.name.concat( " " ).substring( 0, 5 ) ); System.out.print( " " + (g.name. + " ").substring( 0, 5 ) );
There are many other ways to do this, but variations on this quick and dirty solution are the easiest to code using the available Java library string methods.
a) What new instance variable must be added to class Gate to make it possible for printValue() to do its job. (0.5 points)
We need to remember the previous value printed.
b) Explain how a 2-dimensional array of strings can be used to do the bulk of the work done by printValue(). (0.5 points)
Consider the array printValues[current][previous], a 3 by 3 array of strings, where the first index is the current output value of the gate, and the second index is the previous output of the gate. The array could be initialized like this:
printValues[0][0] = "| "; printValues[0][1] = " _| "; printValues[0][2] = " ___|"; printValues[1][0] = "|_ "; printValues[1][1] = " | "; printValues[1][2] = " _|"; printValues[2][0] = "|___ "; printValues[2][1] = " |_ "; printValues[2][2] = " |";
We could even generalize this to allow such things as:
a) What additional instance variable or variables would you add to class Gate to allow something approximating this more complex output format? (0.5 points)
We could use a string to record the changes. Initially, the 5-character string would be blank with a vertical bar in one of 3 positions corresponding to the logic value as of the last print event. With each output change event, the string would be edited.
a) Briefly describe how you would use the data from part a) to create the output desired. Do not give code! (0.5 points)
On an output change event, array elements would change from space to underline except at the new output level, where it would remain blank. Array elements that were already underlines would change to dash, and array elements that were already dashes would change to equals signs.