• Active Topics 

What does this Java code do?

Post Reply
User avatar
Admin
Site Admin
Senior Expert Member
Reactions: 56
Posts: 383
Joined: 10 years ago
Has thanked: 38 times
Been thanked: 32 times
Contact:

#1

  1. package com.pragmatouch.calculator;
  2.  
  3. import java.text.DecimalFormat;
  4. import java.text.NumberFormat;
  5. import java.util.Iterator;
  6. import java.util.Stack;
  7. import android.app.Activity;
  8. import android.os.Bundle;
  9. import android.widget.AdapterView;
  10. import android.widget.Button;
  11. import android.widget.TextView;
  12. import android.widget.AdapterView.OnItemClickListener;
  13. import android.widget.GridView;
  14. import android.view.View;
  15. import android.view.View.OnClickListener;
  16.  
  17. public class main extends Activity {
  18.     GridView mKeypadGrid;
  19.     TextView userInputText;
  20.     TextView memoryStatText;
  21.  
  22.     Stack<String> mInputStack;
  23.     Stack<String> mOperationStack;
  24.  
  25.     KeypadAdapter mKeypadAdapter;
  26.     TextView mStackText;
  27.     boolean resetInput = false;
  28.     boolean hasFinalResult = false;
  29.  
  30.     String mDecimalSeperator;
  31.     double memoryValue = Double.NaN;
  32.  
  33.     /** Called when the activity is first created. */
  34.     @Override
  35.     public void onCreate(Bundle savedInstanceState) {
  36.         super.onCreate(savedInstanceState);
  37.  
  38.         DecimalFormat currencyFormatter = (DecimalFormat) NumberFormat
  39.                 .getInstance();
  40.         char decimalSeperator = currencyFormatter.getDecimalFormatSymbols()
  41.                 .getDecimalSeparator();
  42.         mDecimalSeperator = Character.toString(decimalSeperator);
  43.  
  44.         setContentView(R.layout.main);
  45.  
  46.         // Create the stack
  47.         mInputStack = new Stack<String>();
  48.         mOperationStack = new Stack<String>();
  49.  
  50.         // Get reference to the keypad button GridView
  51.         mKeypadGrid = (GridView) findViewById(R.id.grdButtons);
  52.  
  53.         // Get reference to the user input TextView
  54.         userInputText = (TextView) findViewById(R.id.txtInput);
  55.         userInputText.setText("0");
  56.  
  57.         memoryStatText = (TextView) findViewById(R.id.txtMemory);
  58.         memoryStatText.setText("");
  59.  
  60.         mStackText = (TextView) findViewById(R.id.txtStack);
  61.  
  62.         // Create Keypad Adapter
  63.         mKeypadAdapter = new KeypadAdapter(this);
  64.  
  65.         // Set adapter of the keypad grid
  66.         mKeypadGrid.setAdapter(mKeypadAdapter);
  67.  
  68.         // Set button click listener of the keypad adapter
  69.         mKeypadAdapter.setOnButtonClickListener(new OnClickListener() {
  70.             @Override
  71.             public void onClick(View v) {
  72.                 Button btn = (Button) v;
  73.                 // Get the KeypadButton value which is used to identify the
  74.                 // keypad button from the Button's tag
  75.                 KeypadButton keypadButton = (KeypadButton) btn.getTag();
  76.  
  77.                 // Process keypad button
  78.                 ProcessKeypadInput(keypadButton);
  79.             }
  80.         });
  81.  
  82.         mKeypadGrid.setOnItemClickListener(new OnItemClickListener() {
  83.             public void onItemClick(AdapterView<?> parent, View v,
  84.                     int position, long id) {
  85.  
  86.             }
  87.         });
  88.  
  89.     }
  90.  
  91.     private void ProcessKeypadInput(KeypadButton keypadButton) {
  92.         //Toast.makeText(this, keypadButton.getText(), Toast.LENGTH_SHORT).show();
  93.         String text = keypadButton.getText().toString();
  94.         String currentInput = userInputText.getText().toString();
  95.  
  96.         int currentInputLen = currentInput.length();
  97.         String evalResult = null;
  98.         double userInputValue = Double.NaN;
  99.  
  100.         switch (keypadButton) {
  101.         case BACKSPACE: // Handle backspace
  102.             // If has operand skip backspace
  103.             if (resetInput)
  104.                 return;
  105.  
  106.             int endIndex = currentInputLen - 1;
  107.  
  108.             // There is one character at input so reset input to 0
  109.             if (endIndex < 1) {
  110.                 userInputText.setText("0");
  111.             }
  112.             // Trim last character of the input text
  113.             else {
  114.                 userInputText.setText(currentInput.subSequence(0, endIndex));
  115.             }
  116.             break;
  117.         case SIGN: // Handle -/+ sign
  118.             // input has text and is different than initial value 0
  119.             if (currentInputLen > 0 && currentInput != "0") {
  120.                 // Already has (-) sign. Remove that sign
  121.                 if (currentInput.charAt(0) == '-') {
  122.                     userInputText.setText(currentInput.subSequence(1,
  123.                             currentInputLen));
  124.                 }
  125.                 // Prepend (-) sign
  126.                 else {
  127.                     userInputText.setText("-" + currentInput.toString());
  128.                 }
  129.             }
  130.             break;
  131.         case CE: // Handle clear input
  132.             userInputText.setText("0");
  133.             break;
  134.         case C: // Handle clear input and stack
  135.             userInputText.setText("0");
  136.             clearStacks();
  137.             break;
  138.         case DECIMAL_SEP: // Handle decimal seperator
  139.             if (hasFinalResult || resetInput) {
  140.                 userInputText.setText("0" + mDecimalSeperator);
  141.                 hasFinalResult = false;
  142.                 resetInput = false;
  143.             } else if (currentInput.contains("."))
  144.                 return;
  145.             else
  146.                 userInputText.append(mDecimalSeperator);
  147.             break;
  148.         case DIV:
  149.         case PLUS:
  150.         case MINUS:
  151.         case MULTIPLY:
  152.             if (resetInput) {
  153.                 mInputStack.pop();
  154.                 mOperationStack.pop();
  155.             } else {
  156.                 if (currentInput.charAt(0) == '-') {
  157.                     mInputStack.add("(" + currentInput + ")");
  158.                 } else {
  159.                     mInputStack.add(currentInput);
  160.                 }
  161.                 mOperationStack.add(currentInput);
  162.             }
  163.  
  164.             mInputStack.add(text);
  165.             mOperationStack.add(text);
  166.  
  167.             dumpInputStack();
  168.             evalResult = evaluateResult(false);
  169.             if (evalResult != null)
  170.                 userInputText.setText(evalResult);
  171.  
  172.             resetInput = true;
  173.             break;
  174.         case CALCULATE:
  175.             if (mOperationStack.size() == 0)
  176.                 break;
  177.  
  178.             mOperationStack.add(currentInput);
  179.             evalResult = evaluateResult(true);
  180.             if (evalResult != null) {
  181.                 clearStacks();
  182.                 userInputText.setText(evalResult);
  183.                 resetInput = false;
  184.                 hasFinalResult = true;
  185.             }
  186.             break;
  187.         case M_ADD: // Add user input value to memory buffer
  188.             userInputValue = tryParseUserInput();
  189.             if (Double.isNaN(userInputValue))
  190.                 return;
  191.             if (Double.isNaN(memoryValue))
  192.                 memoryValue = 0;
  193.             memoryValue += userInputValue;
  194.             displayMemoryStat();
  195.  
  196.             hasFinalResult = true;
  197.  
  198.             break;
  199.         case M_REMOVE: // Subtract user input value to memory buffer
  200.             userInputValue = tryParseUserInput();
  201.             if (Double.isNaN(userInputValue))
  202.                 return;
  203.             if (Double.isNaN(memoryValue))
  204.                 memoryValue = 0;
  205.             memoryValue -= userInputValue;
  206.             displayMemoryStat();
  207.             hasFinalResult = true;
  208.             break;
  209.         case MC: // Reset memory buffer to 0
  210.             memoryValue = Double.NaN;
  211.             displayMemoryStat();
  212.             break;
  213.         case MR: // Read memoryBuffer value
  214.             if (Double.isNaN(memoryValue))
  215.                 return;
  216.             userInputText.setText(doubleToString(memoryValue));
  217.             displayMemoryStat();
  218.             break;
  219.         case MS: // Set memoryBuffer value to user input
  220.             userInputValue = tryParseUserInput();
  221.             if (Double.isNaN(userInputValue))
  222.                 return;
  223.             memoryValue = userInputValue;
  224.             displayMemoryStat();
  225.             hasFinalResult = true;
  226.             break;
  227.         default:
  228.             if (Character.isDigit(text.charAt(0))) {
  229.                 if (currentInput.equals("0") || resetInput || hasFinalResult) {
  230.                     userInputText.setText(text);
  231.                     resetInput = false;
  232.                     hasFinalResult = false;
  233.                 } else {
  234.                     userInputText.append(text);
  235.                     resetInput = false;
  236.                 }
  237.  
  238.             }
  239.             break;
  240.  
  241.         }
  242.  
  243.     }
  244.  
  245.     private void clearStacks() {
  246.         mInputStack.clear();
  247.         mOperationStack.clear();
  248.         mStackText.setText("");
  249.     }
  250.  
  251.     private void dumpInputStack() {
  252.         Iterator<String> it = mInputStack.iterator();
  253.         StringBuilder sb = new StringBuilder();
  254.  
  255.         while (it.hasNext()) {
  256.             CharSequence iValue = it.next();
  257.             sb.append(iValue);
  258.  
  259.         }
  260.  
  261.         mStackText.setText(sb.toString());
  262.     }
  263.  
  264.     private String evaluateResult(boolean requestedByUser) {
  265.         if ((!requestedByUser && mOperationStack.size() != 4)
  266.                 || (requestedByUser && mOperationStack.size() != 3))
  267.             return null;
  268.  
  269.         String left = mOperationStack.get(0);
  270.         String operator = mOperationStack.get(1);
  271.         String right = mOperationStack.get(2);
  272.         String tmp = null;
  273.         if (!requestedByUser)
  274.             tmp = mOperationStack.get(3);
  275.  
  276.         double leftVal = Double.parseDouble(left.toString());
  277.         double rightVal = Double.parseDouble(right.toString());
  278.         double result = Double.NaN;
  279.  
  280.         if (operator.equals(KeypadButton.DIV.getText())) {
  281.             result = leftVal / rightVal;
  282.         } else if (operator.equals(KeypadButton.MULTIPLY.getText())) {
  283.             result = leftVal * rightVal;
  284.  
  285.         } else if (operator.equals(KeypadButton.PLUS.getText())) {
  286.             result = leftVal + rightVal;
  287.         } else if (operator.equals(KeypadButton.MINUS.getText())) {
  288.             result = leftVal - rightVal;
  289.  
  290.         }
  291.  
  292.         String resultStr = doubleToString(result);
  293.         if (resultStr == null)
  294.             return null;
  295.  
  296.         mOperationStack.clear();
  297.         if (!requestedByUser) {
  298.             mOperationStack.add(resultStr);
  299.             mOperationStack.add(tmp);
  300.         }
  301.  
  302.         return resultStr;
  303.     }
  304.  
  305.     private String doubleToString(double value) {
  306.         if (Double.isNaN(value))
  307.             return null;
  308.  
  309.         long longVal = (long) value;
  310.         if (longVal == value)
  311.             return Long.toString(longVal);
  312.         else
  313.             return Double.toString(value);
  314.  
  315.     }
  316.  
  317.     private double tryParseUserInput() {
  318.         String inputStr = userInputText.getText().toString();
  319.         double result = Double.NaN;
  320.         try {
  321.             result = Double.parseDouble(inputStr);
  322.  
  323.         } catch (NumberFormatException nfe) {
  324.         }
  325.         return result;
  326. }
  327.  
  328.     private void displayMemoryStat() {
  329.         if (Double.isNaN(memoryValue)) {
  330.             memoryStatText.setText("");
  331.         } else {
  332.             memoryStatText.setText("M = " + doubleToString(memoryValue));
  333.         }
  334.     }
  335. }

See source
0
TSSFL Stack is dedicated to empowering and accelerating teaching and learning, fostering scientific research, and promoting rapid software development and digital technologies
Post Reply

Return to “Java Programming”

  • Information
  • Who is online

    Users browsing this forum: No registered users and 0 guests