制作计算器但无法检索功能

时间:2014-03-29 22:14:18

标签: android string parsing integer calculator

制作Android计算器的一个简单方法是拥有3个单独的编辑文本框,并让用户输入一个数字,一个函数,然后另一个数字,如3 + 3.这将使应用程序开发更容易存储数字和功能并进行计算。

现在......我的计算器应用程序能够实时输出所有输入,不利的一面是,当我检索输入框中的内容时,我将其检索为字符串(以确保我包括输入的所有功能)。我知道如何检索数字(通过使用int解析),但我如何检索诸如+ - / *之类的函数? (他们是主要的!!:O)。任何帮助我都非常感谢谢谢:)

2 个答案:

答案 0 :(得分:0)

您可以将运算符作为字符串获取并使用if语句来确定要执行的操作:

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

    if (operator.equals("+")){
      //addition code here
    }
    else if (operator.equals("-")){
      //subtraction code here
    }
    ...

答案 1 :(得分:0)

尝试使用分析和识别正确操作的开关。像这样的东西: (我假设函数EditText的内容名为functionSign

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

编辑2: 我想用户只能放置函数simbols + - / *并且操作是按方法组织的:

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;
}

此代码是一个非常简单的示例,您必须确保用户不要尝试计算不完整的内容,例如:

  • 3 + 3 -
  • / 3 * 5

和类似的。用户应该做的是你的决定