0

I'm making a calculator, and some computations require 3 pieces of information (eg, 3*4), whereas other only require 2 (eg, 5!).

I have managed to split the input into 3 parts using the following code:

String[] parts = myInput.split(" ");
String num1 = parts[0];
String operation = parts[1];
String num2 = parts[2];

But this means that when I only type 2 things, it doesn't work.

How can I allow for either 3 or 2 things as an input?

Joshua
  • 25
  • 5
  • I think you'll need to check the size of the array and use that to determine the logic 2 vs 3 inputs. – user3298823 Feb 15 '16 at 19:45
  • 1
    What you are looking for is a math parser. Take a look at the answers to this question: http://stackoverflow.com/questions/114586/smart-design-of-a-math-parser – Saba Jamalian Feb 15 '16 at 19:46
  • splitting with white space is not correct. you should check charterer by charter and see if what you got is operand number or operator. that you will know if you have to stop (for operator like factorial) or continue to look for the other operand. – LeTex Feb 15 '16 at 19:48
  • To whomever down voted the question, at least post why you did it. – Tyler Smith Feb 15 '16 at 19:48
  • Why do you need to input the entire expression? Why not capture a set of numeric characters separated by an operator? You can use the `Scanner` class to get the next double and as many operators ( +, -, *, /, or = ) as a character. You can then evaluate the character and perform the appropriate operation once the second operand is entered. – hfontanez Feb 15 '16 at 21:50

2 Answers2

0

You should not assume that the input will always in the 3 parameter form. Rather, take a generic input, parse on it based on use cases. In your case, it boils down to two specific use cases AFTER you accept the input:

  1. Operators that operate on single operand - unary operator
  2. Operators that operate on double operand - binary operator

For each case, you can define a list of operators allowed. E.g. '!' will be in case 1 list, while '*' will be in case '2'

scan through the string, look for the operator position. [^0-9] (represents a pattern which other than numbers). Or simply you can do a trivial check for the operator (by creating your own custom method)

Once you have figured out this, validate your string (optional) - e.g. makes no sense to have two operands for a unary operator.

Having done this, it is fairly easy to parse now the required operands by splitting out the string based on the operator. Computation is fairly trivial then.

Hope this helps.

mohitm
  • 153
  • 10
-1

Without knowing more I can't help you find a better design to accommodate for the commonalities and variances. But to answer the stated questions....

You can use parts.length to know many variables you were given and use that to branch your code (i.e. if else statement).

Tyler Smith
  • 531
  • 1
  • 5
  • 23