2014-03-29 47 views
0

一個簡單的方法,使一個機器人計算器將有3個獨立的編輯文本框,並在用戶把一個號碼,功能,然後像3 + 3其他號碼。這將使應用程序開發者更容易存儲數字和函數並執行計算。製作一個計算器,但沒有辦法找回功能

現在...我的計算器應用程序能夠將所有輸入實時輸出,當我檢索輸入框中的內容時,我將它作爲字符串檢索(以確保包含所有輸入功能輸入)。我知道如何檢索數字(通過使用int解析),但我如何檢索功能,如+ -/*? (他們是主要的!!:O)。任何幫助將我非常讚賞謝謝:)

回答

0

嘗試使用一個開關,分析並識別正確的操作。事情是這樣的: (我猜想功能的EditText在一個名爲functionSign

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

EDIT 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

和類似。什麼是用戶應該能夠做的就是你的

決定
+0

但是如果有像4 + 6-11 + 10-14那樣的東西呢? – sudoman

+0

向我澄清一件事:用戶如何插入操作?你談到了3 EditText,所以我想用戶可以一次插入一個操作。 – MatteoM

+0

nope,我已經這樣做了,只要用戶插入一個數字/函數,它就會立即顯示在屏幕上的1個編輯文本框中(因此只有一個輸入位置) – sudoman

0

你可以得到運營商作爲一個字符串,並使用if語句來決定做什麼:

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

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

那怎麼我已經做到了,所以,如果用戶增加,我得到了什麼是已經在輸出框如(8 + 7 + 8 + 2 + 3),以及(+ 8 + 7 + 8 + 2 + 3 +)它會以字符串的形式檢索/存儲? – sudoman

相關問題