Problem Statement
You are writing the embedded software to make sure a calculator functions properly. This is a special calculator that allows simple arithmetic with very large integers. The following rules are in place for PROPER USAGE (quotes used for clarity):
1) A valid calculation consists of <NUMBER><OPERATOR><NUMBER><EQUALS> where:
- <NUMBER> is a string of one or more digits('0'..'9')
- <OPERATOR> is one of '+','-','*','/'
- <EQUALS> is '='
2) The calculator can perform a sequence of valid calculations in a row.
- So 98+01234=234*1230=000/000= is valid where
- 98+01234= is the first calculation,
- 234*1230= is the second and
- 000/000= is the last.
Embedded logic is needed to determine what the next key-press should be. Your function will return what key-press the calculator can accept next according to the following schema (quotes used for clarity):
Next key-press : Return
--------------------------------------------------------
Digit ('0'..'9') : 1
Operator ('+','-','*','/') : 2
Digit or Operator ('0'..'9','+','-','*','/') : 3
Equals ('=') : 4
Digit or Equals ('0'..'9','=') : 5
For example, if you have:
"47"
The next key-press could either be a Digit or an Operator so you would return 3.
If the input given doesn't follow the above laws of PROPER USAGE you should
return 0. This means that invalid key-presses occurred previously and your
calculator is no longer in a functioning state. For example, if you have:
"53++6=12+"
The input has 2 consecutive Operator key-presses("++") so the entire input
violates PROPER USAGE and you will return 0.
Create a class MathDebug that contains the method getNext, which takes a String, input, and returns an int that represents valid next key-presses or 0 if there is an error in the input.
Definition
- Class:
- MathDebug
- Method:
- getNext
- Parameters:
- String
- Returns:
- int
- Method signature:
- int getNext(String input)
- (be sure your method is public)
Constraints
- input will only contain characters within the following string: "0123456789+-*/=" (quotes are for clarity).
- input will have length between 0 and 50 characters, inclusive.
Examples
"1+2="
Returns: 1
Thus far we have <NUMBER><OPERATOR><NUMBER><EQUALS> which is one valid calculation. We can now accept another valid calculation of the form <NUMBER><OPERATOR><NUMBER><EQUALS>. Since <NUMBER> is next we will only accept a Digit key-press."123+"
Returns: 1
Thus far we have <NUMBER><OPERATOR> so we need the next <NUMBER>. The only possible key-press is Digit since if, Equal was given, the second <NUMBER> would have a length of 0.""
Returns: 1
No input has been given thus far so we are waiting for a Digit key-press."1"
Returns: 3
The next key-press could be either a Digit or an Operator."=123+456="
Returns: 0
The input started with an '=' which is an invalid key-press so the entire computation is invalid."1234+123=98*0"
Returns: 5
"98+01234=234*1230=000/000="
Returns: 1
"98+76+23="
Returns: 0