CMPS 144L
Lab Activity: Loop Invariant for Numeral2Number

Complete the numeralToNumber() method in the Java class Numeral2Number. Its purpose is to compute the integer value represented by the decimal integer numeral passed to it as an argument (and thus it is a re-implementation of the Integer.parseInt() method in Java's standard library).

By "decimal integer numeral" we mean a String composed entirely of decimal digit characters, which are those in the range '0'..'9'. For example, the method should translate the string "80324" into the value given by the integer literal 80324.

The loop invariant is that the value of the int variable result is equal to the integer described by the first i characters of the given numeral. (Of course, i is the loop control variable.)

All that's left for you to do is to fill in the missing right-hand side of the assignment statement that updates result within the loop body. (Of course, you are not allowed to introduce code that results in a call to the Integer.parseInt() method.) The program includes assert statements to verify that the loop invariant is true immediately before and immediately after each loop iteration. By default, assertions are disabled in Java, which means that they have no effect. To enable them, follow these instructions.

An example should provide you with the insight needed to complete the statement. Suppose that the numeral to be translated into an int value were "54321" and the loop had reached the point that i == 3. Then the loop invariant implies that result == 543 (543 being the integer translation of the prefix of length three of "54321").

During each loop iteration, i is incremented, so result must be updated accordingly. In our example, i will be incremented from 3 to 4, which means that result should be updated from having the value 543 to having the value 5432. What is the relationship between those two numbers? Clearly, the latter is ten times the former, plus two. (Now, if the given numeral had been "543789", the value of result should have been updated from 543 to 5437, which is ten times 543, plus seven. It is left to the student to apprehend the relevant generalization of these examples.)

To test your work, the class includes a main() method that expects to receive one argument, that being a decimal integer numeral to be translated into the integer that it describes. If you don't know how to supply an application program with "command line" arguments (or what jGrasp refers to as "run" arguments), ask your GTA. Or read this.