Question

An easy way to make an android calculator would be to have 3 separate edit text boxes and have the user in put a number, a function, and then another number like 3 + 3. This would make it easier for the app dev to store the number(s) and function(s) and perform a calculation.

Now... my calculator app has the ability to out put all the input real-time, the down side is that when I retrieve what's in the input box, i retrieve it as string (to make sure i include all the functions input-ed). I know how to retrieve numbers (by using int parse) but how do I retrieve the functions such as + - / * ? (They're the main bit!! :O). Any help would me much appreciated thanks :)

Was it helpful?

Solution

Try to use a switch that analyze and identify the correct operation. Something like this: (I suppose the content of function EditText in a string named functionSign

...
switch(functionSign)
{
case "+": return op1+op2;
case "-": return op1-op2;
...

EDIT 2: I suppose that user can put only the functions simbols + - / * and the operations are organized in a method:

public double calculate()
{
  String operations= inputEditText.getText().toString();
  StringTokenizer st= new StringTokenizer(operations); 
  //to calculate in input must have at last one operation and two operands
  //the first token must be a number (the operation scheme is (number)(function)(numeber)...)
  double result=Double.parseDouble(st.nextToken());
  while(st.hasMoreTokens())
  {
    String s=st.nextToken();

    if(s.equals("+")) 
       result += Double.parseDouble(st.nextToken());
    else if(s.equals("-"))
       result -= Double.parseDouble(st.nextToken());
    else if(s.equals("*"))
       result *= Double.parseDouble(st.nextToken());
    else if(s.equals("/"))
       result /= Double.parseDouble(st.nextToken());
    else
       throw new Exception();
  }
  return result;
}

This code is a really simple example, you must be sure that the user don't try to calculate something incomplete like:

  • 3 + 3 -
  • / 3 * 5

and similar. What the user should be able to do is your decision

OTHER TIPS

You can get the operator as a string and use if statements to determine what to do:

    String operator=operatorEditText.getText().toString();

    if (operator.equals("+")){
      //addition code here
    }
    else if (operator.equals("-")){
      //subtraction code here
    }
    ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top