S. Matsueda - 2 years ago 95
Java Question

# Check to see if a math equation with numbers have numbers with ONLY ONE digit

I am making a program resembling the game 24.

I need to check a user's input (a math equation using four random numbers provided by the program) to see if the numbers given by the user only have ONE digit.

For example:

The program spits out 6 4 9 5

The user could enter 9 + 5 + 6 + 4 (which equals 24).

But I would not want them to be able to do anything like 95 - 64 (not right, just an example) to make 24.

How would I check to see if the numbers in the equation are only one digit?

/**
* Accepts the user's math problem.
* Then...
* Makes sure the entered math problem follows the rules and equals 24.
* Rules: Must have at least one symbol of multiplication, division, addition, or subtraction.
* The numbers entered only have one digit.
* The problem equals 24.
* @param none
* @return true or false
* if the problem follows the rules and equals 24 - true (player wins)
* if the problem doesn't follow the rules and equals 24 - false (player loses)
* if the problem doesn't follow the rules and doesn't equal 24 - false (player loses)
*

*/
public void mathProblem()
{
Scanner scan = new Scanner(System.in);

``````    System.out.println("");
String response = scan.nextLine();

boolean done = false;

while (!done)
{
if (response.contains("*") || response.contains("/") || response.contains("+") || response.contains("-"))
{
//If statement to check and see if numbers in response ONLY have ONE number.
}

else if (!response.contains("*") || !response.contains("/") || !response.contains("+") || !response.contains("-"))
{
done = true;
}
}
}
``````

One way of checking the input would be to use a regular expression. For example:

``````if (!Pattern.matches("(\\s*\\d\\s*[+-*/]){3}+\\s*\\d", input)) {
...
}
``````

That expression allows only one digit numbers and automatically ignores whitespace and checks valid operators (avoiding all your contains statements). Even better, you can add capturing groups to the expression to automatically get the digits and operators out of the input.

``````Pattern pattern = Pattern.compile("\\s*(\\d)\\s*([+-*/])\\s*(\\d)\\s*([+-*/])\\s*(\\d)\\s*([+-*/])\\s*(\\d)");
Matcher matcher = pattern.matcher(input);
while (!matcher.matches()) {
// print error and accept new input
matcher = pattern.matcher(input);
}

int result = Integer.parseInt(matcher.group(1));
for (int g = 2; g <=6; g+= 2) {
switch (matcher.group(g)) {
case '*':
result *= Integer.parseInt(matcher.group(g + 1));
break;
case '+':
result += Integer.parseInt(matcher.group(g + 1));
break;
// and so on
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download