Monday, June 18, 2018

Android simpleCalculator

  1. package com.example.mycs.simplecalculator;
  2.  
  3. import android.support.v7.app.AppCompatActivity;
  4. import android.os.Bundle;
  5. import android.view.View;
  6. import android.widget.Button;
  7. import android.widget.TextView;
  8.  
  9. import java.util.HashSet;
  10. import java.util.Set;
  11.  
  12. public class MainActivity extends AppCompatActivity {
  13.  
  14. private TextView result;
  15. private String operand;
  16. private String operator;
  17. private Set numbers;
  18. private Set operators;
  19. @Override
  20. protected void onCreate(Bundle savedInstanceState) {
  21. super.onCreate(savedInstanceState);
  22. setContentView(R.layout.activity_main);
  23. result = findViewById(R.id.result);
  24. }
  25. private void initNumbers() {
  26. numbers = new HashSet();
  27. for (int i = 0; i < 10; i++)
  28. numbers.add(Integer.toString(i));
  29. numbers.add(".");
  30. }
  31. private void initOperators() {
  32. operators = new HashSet();
  33. String[] oprs = {"+", "-", "*", "/"};
  34. for (String operator: oprs)
  35. operators.add(operator);
  36. }
  37. public void handleClick(View view) {
  38. Button clicked = (Button) view;
  39. String label = clicked.getText().toString();
  40. String display = result.getText().toString();
  41. if (isClear(label))
  42. result.setText(R.string.result_default);
  43. else if (isNumerical(label)) {
  44. if (isDefaultResult(display) || isOperator(display))
  45. result.setText(label);
  46. else
  47. result.setText(display + label);
  48. }
  49. else if (isOperator(label)) {
  50. operator = label;
  51. operand = display;
  52. result.setText(label);
  53. }
  54. else if (label.equals("=")) {
  55. double a, b, c;
  56. if (operator == null || operand == null)
  57. return;
  58. try {
  59. a = Double.parseDouble(operand);
  60. b = Double.parseDouble(display);
  61. }
  62. catch (Exception e) {
  63. System.out.println(e.getMessage());
  64. return;
  65. }
  66. if (operator.equals("+"))
  67. c = a + b;
  68. else if (operator.equals("-"))
  69. c = a - b;
  70. else if (operator.equals("*"))
  71. c = a * b;
  72. else
  73. c = a / b;
  74. operand = Double.toString(c);
  75. result.setText(operand);
  76. }
  77. }
  78. private boolean isClear(String value) {
  79. return value.equals(getString(R.string.buttonClear));
  80. }
  81. private boolean isOperator(String value) {
  82. if (operators == null)
  83. initOperators();
  84. return operators.contains(value);
  85. }
  86. private boolean isDefaultResult(String value) {
  87. return value.equals(getString(R.string.result_default));
  88. }
  89. private boolean isNumerical(String value) {
  90. if (numbers == null)
  91. initNumbers();
  92. return numbers.contains(value);
  93. }
  94. }

No comments:

Post a Comment