class InvalidInput extends Exception {
String token;
public String getToken () { return token; }
public InvalidInput(String badInput) {
token = badInput;
}
}
int quotient(Scanner input) throws InvalidInput {
int divisor, dividend;
if (input.hasNextInt())
divisor = input.nextInt();
else
throw new InvalidInput(input.next());
if (input.hasNextInt())
dividend = input.nextInt();
else
throw new InvalidInput(input.next());
return divisor / dividend;
}
try {
System.out.printf("quotient = %d\n", p.quotient(input));
}
catch (InvalidInput ie) {
System.out.printf("Invalid input: %s must be an integer\n", ie.getToken());
}
catch (ArithmeticException e) { System.out.println(e); }
| E -> - E E | E -> - E E |
| E -> - number E | E -> number |
| E -> - number + E E | E -> E -> + E E |
| E -> - number + - E E E | E -> E -> - E E |
| E -> - number + - number E E | E -> number |
| E -> - number + - number number E | E -> number |
| E -> - number + - number number number | E -> number |
-------E---------
| | |
- E ----E-----------------
| | | |
number + ----E------- E
| | | |
- E E number
| |
number number
Set 1: E' -> E.
Set 2: E -> number.
Set 3: E -> - .E E | .number | .- E E | .+ E E
Set 4: E -> + .E E | .number | .- E E | .+ E E
| Input | Stack | Action |
| -(id)$$ | 1 | shift - and move to state 4 |
| (id)$$ | 1-4 | shift ( and move to state 3 |
| id)$$ | 1-4(3 | shift id and move to state 5 |
| )$$ | 1-4(3id5 | reduce by E->id, pop 1 pair, shift E, and move to state 8 |
| )$$ | 1-4(3E8 | shift ) and move to state 12 |
| $$ | 1-4(3E8)12 | reduce by E->(E), pop 3 pairs, shift E, and move to state 9 |
| $$ | 1-4E9 | reduce by E->-E, pop 2 pairs, shift E, and move to state 1 |
| $$ | 1E2 | accept the string |