/* Java class that includes a method that translates a given integer ** numeral (i.e., a String composed of decimal digit characters) into ** the corresponding integer value. (In other words, the method ** re-implements the Integer.parseInt() method found in Java's standard ** library.) The point is to illustrate the development of a loop that ** conforms to a proposed loop invariant. ** ** Authors: R. McCloskey and < STUDENTS' NAMES > */ public class Numeral2Number { /* Returns the integer value described by the given numeral, which ** is assumed to be a sequence of decimal digits. ** Example: The numeral "5834" yields the int value 5834 ** pre: Letting N = numeral.length(): ** N > 0 and ** for all i in [0..N), numeral.charAt(i) is one of '0', '1', ..., '9'. ** post: value returned is Integer.parseInt(numeral) */ public static int numeralToNumber(String numeral) { // Introduce local variable N as a convenient shorthand. final int N = numeral.length(); int result = digitToNum(numeral.charAt(0)); int i = 1; // pre-loop loop invariant check: assert result == Integer.parseInt(numeral.substring(0,i)); while (i != N) { result = ??; i = i+1; // Verify loop invariant at end of each iteration: assert result == Integer.parseInt(numeral.substring(0,i)); } assert result == Integer.parseInt(numeral); return result; } //Note: The loop invariant says that the value of 'result' is the // number represented by the prefix of length i of 'numeral' /* Given a digit character (i.e., one of '0', '1', '2', ..., '9'), ** returns the corresponding numeric value (of type int). */ private static int digitToNum(char digit) { return digit - '0'; } /* This method expects to receive a single argument that is a ** decimal integer numeral (meaning a string of digit characters, ** like "80345"). It calls the numeralToNumber() method to compute ** the corresponding integer value and reports the results. */ public static void main(String[] args) { String theNumeral = args[0]; // Call numeralToNumber() to compute the number described by // the given numeral and report the result. int number = numeralToNumber(theNumeral); System.out.printf("The integer represented by numeral \"%s\" is %d\n", theNumeral, number); } }