当前位置:   article > 正文

实现简单的Android计算器_安卓计算器代码

安卓计算器代码

目录

设置UI

实现计算器的代码

按钮点击的实现

 处理输入的表达式

中缀转后缀的函数

计算函数

效果图


设置UI

        首先,让我们先来设置UI。

        在res资源找到values文件夹,右键设置style.xlm文件,即为按钮的样式

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. <style name="ButtonStyle" >
  4. <item name="android:radius">10dp</item>
  5. <item name="android:textStyle">bold</item>
  6. <item name="android:textSize">20sp</item>
  7. <item name="android:color">#000</item>
  8. <item name="android:borderlessButtonStyle">@style/TextAppearance.AppCompat.Body1</item>
  9. </style>
  10. </resources>

        其次,让我们在res下的drawable文件夹下新建一个select文件 ,里面是关于按钮的一些的形状、背景颜色、以及点击时变色的设置

        注意:颜色可以按照自己选择的背景图来设置,而不是照搬

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">
  3. <item android:state_pressed="false">
  4. <shape android:shape="rectangle">
  5. <solid android:color="#98FF98"/>
  6. <stroke android:width="5dp"/>
  7. </shape>
  8. </item>
  9. <item android:state_pressed="true">
  10. <shape android:shape="rectangle">
  11. <solid android:color="#64E986"/>
  12. <stroke android:width="5dp"/>
  13. </shape>
  14. </item>
  15. </selector>

        让我们重新回到activity_main.xlm,这里,我使用的是表格布局嵌套线性布局

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:layout_gravity="center"
  8. android:gravity="center"
  9. android:background="@drawable/background"
  10. android:alpha="1"
  11. tools:context=".MainActivity">
  12. <EditText
  13. android:id="@+id/edit"
  14. android:layout_width="match_parent"
  15. android:layout_height="225dp"
  16. android:textSize="40dp"
  17. android:gravity="right"
  18. android:cursorVisible="false"
  19. android:hint="0"
  20. android:ellipsize="end"/>
  21. <!-- <TextView-->
  22. <!-- android:id="@+id/text_view"-->
  23. <!-- android:layout_width="match_parent"-->
  24. <!-- android:layout_height="wrap_content"-->
  25. <!-- android:text="0"/>-->
  26. <TableRow>
  27. <Button
  28. android:id="@+id/button_delete"
  29. android:layout_width="90dp"
  30. android:layout_height="90dp"
  31. android:layout_marginLeft="10dp"
  32. style="@style/ButtonStyle"
  33. android:background="@drawable/select"
  34. android:alpha="0.4"
  35. android:gravity="center"
  36. android:layout_marginTop="10dp"
  37. android:text="del" />
  38. <Button
  39. android:id="@+id/button_brackets_left"
  40. android:layout_width="90dp"
  41. android:layout_height="90dp"
  42. android:layout_marginLeft="10dp"
  43. android:layout_marginTop="10dp"
  44. style="@style/ButtonStyle"
  45. android:background="@drawable/select"
  46. android:alpha="0.4"
  47. android:gravity="center"
  48. android:text="(" />
  49. <Button
  50. android:id="@+id/button_brackets_right"
  51. android:layout_width="90dp"
  52. android:layout_height="90dp"
  53. android:layout_marginLeft="10dp"
  54. android:layout_marginTop="10dp"
  55. style="@style/ButtonStyle"
  56. android:background="@drawable/select"
  57. android:alpha="0.4"
  58. android:gravity="center"
  59. android:text=")" />
  60. <Button
  61. android:id="@+id/button_divide"
  62. android:layout_width="90dp"
  63. android:layout_height="90dp"
  64. android:layout_marginLeft="10dp"
  65. style="@style/ButtonStyle"
  66. android:background="@drawable/select"
  67. android:alpha="0.4"
  68. android:gravity="center"
  69. android:layout_marginTop="10dp"
  70. android:text="/" />
  71. </TableRow>
  72. <TableRow>
  73. <Button
  74. android:id="@+id/button_7"
  75. android:layout_width="90dp"
  76. android:layout_height="90dp"
  77. android:layout_marginLeft="10dp"
  78. style="@style/ButtonStyle"
  79. android:background="@drawable/select"
  80. android:alpha="0.4"
  81. android:gravity="center"
  82. android:layout_marginTop="10dp"
  83. android:text="7" />
  84. <Button
  85. android:id="@+id/button_8"
  86. android:layout_width="90dp"
  87. android:layout_height="90dp"
  88. android:layout_marginLeft="10dp"
  89. style="@style/ButtonStyle"
  90. android:background="@drawable/select"
  91. android:alpha="0.4"
  92. android:gravity="center"
  93. android:layout_marginTop="10dp"
  94. android:text="8" />
  95. <Button
  96. android:id="@+id/button_9"
  97. android:layout_width="90dp"
  98. android:layout_height="90dp"
  99. android:layout_marginLeft="10dp"
  100. style="@style/ButtonStyle"
  101. android:background="@drawable/select"
  102. android:alpha="0.4"
  103. android:gravity="center"
  104. android:layout_marginTop="10dp"
  105. android:text="9" />
  106. <Button
  107. android:id="@+id/button_multiply"
  108. android:layout_width="90dp"
  109. android:layout_height="90dp"
  110. android:layout_marginLeft="10dp"
  111. style="@style/ButtonStyle"
  112. android:background="@drawable/select"
  113. android:alpha="0.4"
  114. android:gravity="center"
  115. android:layout_marginTop="10dp"
  116. android:text="*" />
  117. </TableRow>
  118. <TableRow>
  119. <Button
  120. android:id="@+id/button_4"
  121. android:layout_width="90dp"
  122. android:layout_height="90dp"
  123. android:layout_marginLeft="10dp"
  124. style="@style/ButtonStyle"
  125. android:background="@drawable/select"
  126. android:alpha="0.4"
  127. android:gravity="center"
  128. android:layout_marginTop="10dp"
  129. android:text="4" />
  130. <Button
  131. android:id="@+id/button_5"
  132. android:layout_width="90dp"
  133. android:layout_height="90dp"
  134. android:layout_marginLeft="10dp"
  135. style="@style/ButtonStyle"
  136. android:background="@drawable/select"
  137. android:alpha="0.4"
  138. android:gravity="center"
  139. android:layout_marginTop="10dp"
  140. android:text="5" />
  141. <Button
  142. android:id="@+id/button_6"
  143. android:layout_width="90dp"
  144. android:layout_height="90dp"
  145. android:layout_marginLeft="10dp"
  146. style="@style/ButtonStyle"
  147. android:background="@drawable/select"
  148. android:alpha="0.4"
  149. android:gravity="center"
  150. android:layout_marginTop="10dp"
  151. android:text="6" />
  152. <Button
  153. android:id="@+id/button_add"
  154. android:layout_width="90dp"
  155. android:layout_height="90dp"
  156. android:layout_marginLeft="10dp"
  157. style="@style/ButtonStyle"
  158. android:background="@drawable/select"
  159. android:alpha="0.4"
  160. android:gravity="center"
  161. android:layout_marginTop="10dp"
  162. android:text="+" />
  163. </TableRow>
  164. <TableRow>
  165. <Button
  166. android:id="@+id/button_1"
  167. android:layout_width="90dp"
  168. android:layout_height="90dp"
  169. android:layout_marginLeft="10dp"
  170. style="@style/ButtonStyle"
  171. android:background="@drawable/select"
  172. android:alpha="0.4"
  173. android:gravity="center"
  174. android:layout_marginTop="10dp"
  175. android:text="1" />
  176. <Button
  177. android:id="@+id/button_2"
  178. android:layout_width="90dp"
  179. android:layout_height="90dp"
  180. android:layout_marginLeft="10dp"
  181. style="@style/ButtonStyle"
  182. android:background="@drawable/select"
  183. android:alpha="0.4"
  184. android:gravity="center"
  185. android:layout_marginTop="10dp"
  186. android:text="2" />
  187. <Button
  188. android:id="@+id/button_3"
  189. android:layout_width="90dp"
  190. android:layout_height="90dp"
  191. android:layout_marginLeft="10dp"
  192. style="@style/ButtonStyle"
  193. android:background="@drawable/select"
  194. android:alpha="0.4"
  195. android:gravity="center"
  196. android:layout_marginTop="10dp"
  197. android:text="3" />
  198. <Button
  199. android:id="@+id/button_subtract"
  200. style="@style/ButtonStyle"
  201. android:layout_width="90dp"
  202. android:layout_height="90dp"
  203. android:layout_marginLeft="10dp"
  204. android:layout_marginTop="10dp"
  205. android:alpha="0.4"
  206. android:background="@drawable/select"
  207. android:gravity="center"
  208. android:text="-" />
  209. </TableRow>
  210. <TableRow >
  211. <Button
  212. android:id="@+id/button_ac"
  213. android:layout_width="90dp"
  214. android:layout_height="90dp"
  215. android:layout_marginLeft="10dp"
  216. style="@style/ButtonStyle"
  217. android:background="@drawable/select"
  218. android:alpha="0.4"
  219. android:gravity="center"
  220. android:layout_marginTop="10dp"
  221. android:text="AC" />
  222. <Button
  223. android:id="@+id/button_0"
  224. style="@style/ButtonStyle"
  225. android:layout_width="90dp"
  226. android:layout_height="90dp"
  227. android:layout_marginLeft="10dp"
  228. android:layout_marginTop="10dp"
  229. android:alpha="0.4"
  230. android:background="@drawable/select"
  231. android:gravity="center"
  232. android:text="0" />
  233. <!-- android:layout_columnSpan="2"-->
  234. <!-- android:layout_gravity="fill_horizontal"-->
  235. <Button
  236. android:id="@+id/button_point"
  237. style="@style/ButtonStyle"
  238. android:layout_width="90dp"
  239. android:layout_height="90dp"
  240. android:layout_marginLeft="10dp"
  241. android:layout_marginTop="10dp"
  242. android:alpha="0.4"
  243. android:background="@drawable/select"
  244. android:gravity="center"
  245. android:text="." />
  246. <Button
  247. android:id="@+id/button_equal"
  248. style="@style/ButtonStyle"
  249. android:layout_width="90dp"
  250. android:layout_height="90dp"
  251. android:layout_marginLeft="10dp"
  252. android:layout_marginTop="10dp"
  253. android:alpha="0.4"
  254. android:background="@drawable/select"
  255. android:gravity="center"
  256. android:text="=" />
  257. </TableRow>
  258. </TableLayout>

实现计算器的代码

按钮点击的实现

  1. public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  2. public static EditText editText;
  3. public static String string = "";
  4. public static int left = 0;
  5. public static int right = 0;
  6. public static boolean pointFlat = true;
  7. public static boolean isResult = false;
  8. public static Button tempButton;
  9. @Override
  10. protected void onCreate(Bundle savedInstanceState) {
  11. super.onCreate(savedInstanceState);
  12. setContentView(R.layout.activity_main);
  13. Button button1 = (Button) findViewById(R.id.button_1);
  14. Button button2 = (Button) findViewById(R.id.button_2);
  15. Button button3 = (Button) findViewById(R.id.button_3);
  16. Button button4 = (Button) findViewById(R.id.button_4);
  17. Button button5 = (Button) findViewById(R.id.button_5);
  18. Button button6 = (Button) findViewById(R.id.button_6);
  19. Button button7 = (Button) findViewById(R.id.button_7);
  20. Button button8 = (Button) findViewById(R.id.button_8);
  21. Button button9 = (Button) findViewById(R.id.button_9);
  22. Button button0 = (Button) findViewById(R.id.button_0);
  23. Button add = (Button) findViewById(R.id.button_add);
  24. Button subtract = (Button) findViewById(R.id.button_subtract);
  25. Button multiply = (Button) findViewById(R.id.button_multiply);
  26. Button divide = (Button) findViewById(R.id.button_divide);
  27. Button ac = (Button) findViewById(R.id.button_ac);
  28. Button delete = (Button) findViewById(R.id.button_delete);
  29. Button equal = (Button) findViewById(R.id.button_equal);
  30. Button button_left = (Button) findViewById(R.id.button_brackets_left);
  31. Button button_right = (Button) findViewById(R.id.button_brackets_right);
  32. Button point = (Button) findViewById(R.id.button_point);
  33. editText = (EditText) findViewById(R.id.edit);
  34. button1.setOnClickListener(this);
  35. button2.setOnClickListener(this);
  36. button3.setOnClickListener(this);
  37. button4.setOnClickListener(this);
  38. button5.setOnClickListener(this);
  39. button6.setOnClickListener(this);
  40. button7.setOnClickListener(this);
  41. button8.setOnClickListener(this);
  42. button9.setOnClickListener(this);
  43. button0.setOnClickListener(this);
  44. add.setOnClickListener(this);
  45. subtract.setOnClickListener(this);
  46. multiply.setOnClickListener(this);
  47. divide.setOnClickListener(this);
  48. ac.setOnClickListener(this);
  49. delete.setOnClickListener(this);
  50. button_left.setOnClickListener(this);
  51. button_right.setOnClickListener(this);
  52. equal.setOnClickListener(this);
  53. point.setOnClickListener(this);
  54. }
  55. @Override
  56. public void onClick(View view) {
  57. if (isResult){
  58. String tempbutton;
  59. tempButton = (Button) findViewById(view.getId());
  60. // tempButton.setOnClickListener(this);
  61. tempbutton = String.valueOf(tempButton.getText());
  62. if (tempbutton.matches("[\\+\\-\\*\\/]")){
  63. isResult = false;
  64. }else if(tempbutton.equals("=")){
  65. } else if (tempbutton.equals("del")) {
  66. isResult = false;
  67. } else {
  68. string = "";
  69. editText.setText(string);
  70. isResult = false;
  71. }
  72. }
  73. if (view.getId() == R.id.button_1) {
  74. string += "1";
  75. editText.setText(string);
  76. }
  77. if (view.getId() == R.id.button_2) {
  78. string += "2";
  79. editText.setText(string);
  80. }
  81. if (view.getId() == R.id.button_3) {
  82. string += "3";
  83. editText.setText(string);
  84. }
  85. if (view.getId() == R.id.button_4) {
  86. string += "4";
  87. editText.setText(string);
  88. }
  89. if (view.getId() == R.id.button_5) {
  90. string += "5";
  91. editText.setText(string);
  92. }
  93. if (view.getId() == R.id.button_6) {
  94. string += "6";
  95. editText.setText(string);
  96. }
  97. if (view.getId() == R.id.button_7) {
  98. string += "7";
  99. editText.setText(string);
  100. }
  101. if (view.getId() == R.id.button_8) {
  102. string += "8";
  103. editText.setText(string);
  104. }
  105. if (view.getId() == R.id.button_9) {
  106. string += "9";
  107. editText.setText(string);
  108. }
  109. if (view.getId() == R.id.button_0) {
  110. int length_0 = string.length();
  111. if (length_0 > 0 && String.valueOf(string.charAt(length_0 - 1)).equals("/")) {
  112. editText.setText(string + "0" + " tip : 0不能作为除数");
  113. } else {
  114. string += "0";
  115. editText.setText(string);
  116. }
  117. }
  118. if (view.getId() == R.id.button_add) {
  119. int length_add = string.length();
  120. if (length_add == 0){
  121. string = "+";
  122. }else if (String.valueOf(string.charAt(length_add - 1)).equals(".")) {
  123. string += "0+";
  124. } else if (String.valueOf(string.charAt(length_add - 1)).matches("[\\-\\*\\/\\+]")) {
  125. string = string.substring(0,length_add - 1);
  126. string += "+";
  127. } else {
  128. string += "+";
  129. }
  130. editText.setText(string);
  131. pointFlat = true;
  132. }
  133. if (view.getId() == R.id.button_subtract) {
  134. int length_sub = string.length();
  135. if (length_sub == 0) {
  136. string += "-";
  137. } else if (String.valueOf(string.charAt(length_sub - 1)).matches("[\\+\\-\\*\\/]{1}")) {
  138. string += "(0-";
  139. left++;
  140. }//减号前有运算符的情况
  141. else if (String.valueOf(string.charAt(length_sub - 1)).equals(".")) {
  142. string += "0-";
  143. } else {
  144. string += "-";
  145. }
  146. editText.setText(string);
  147. pointFlat = true;
  148. }
  149. if (view.getId() == R.id.button_multiply) {
  150. int length_mul = string.length();
  151. if (length_mul == 0){
  152. string = "*";
  153. } else if (String.valueOf(string.charAt(length_mul - 1)).equals(".")) {
  154. string += "0*";
  155. } else if (String.valueOf(string.charAt(length_mul - 1)).matches("[\\-\\+\\/\\*]")) {
  156. string = string.substring(0,length_mul - 1);
  157. string += "*";
  158. } else {
  159. string += "*";
  160. }
  161. editText.setText(string);
  162. pointFlat = true;
  163. }
  164. if (view.getId() == R.id.button_divide) {
  165. int length_divide = string.length();
  166. if (length_divide == 0){
  167. string = "/";
  168. }else if (String.valueOf(string.charAt(length_divide - 1)).equals(".")) {
  169. string += "0/";
  170. } else if (String.valueOf(string.charAt(length_divide - 1)).matches("[\\+\\*\\-\\/]")) {
  171. string = string.substring(0,length_divide - 1);
  172. string += "/";
  173. } else {
  174. string += "/";
  175. }
  176. editText.setText(string);
  177. pointFlat = true;
  178. }
  179. if (view.getId() == R.id.button_ac) {
  180. string = "";
  181. left = right = 0;
  182. pointFlat = true;
  183. editText.setText(string);
  184. }
  185. if (view.getId() == R.id.button_delete) {
  186. int length_del = string.length();
  187. if (length_del > 0){
  188. String temp = String.valueOf(string.charAt(length_del - 1));
  189. if (temp.equals(".")) {
  190. pointFlat = true;
  191. } else if (temp.equals("(")) {
  192. left--;
  193. } else if (temp.equals(")")) {
  194. right--;
  195. }
  196. string = string.substring(0, length_del - 1);
  197. editText.setText(string);
  198. if (string.equals("")) {
  199. left = right = 0;
  200. pointFlat = true;
  201. isResult = false;
  202. }
  203. }
  204. }
  205. if (view.getId() == R.id.button_brackets_left) {
  206. string += "(";
  207. left++;
  208. editText.setText(string);
  209. }
  210. if (view.getId() == R.id.button_brackets_right) {
  211. int length_right = string.length();
  212. if (string.charAt(length_right - 1) == '.'){
  213. string += "0)";
  214. right++;
  215. editText.setText(string);
  216. }else {
  217. string += ")";
  218. right++;
  219. editText.setText(string);
  220. }
  221. }
  222. if (view.getId() == R.id.button_point) {
  223. if (pointFlat) {
  224. int length_point = string.length();
  225. if (length_point == 0 || (length_point > 0
  226. && String.valueOf(string.charAt(length_point - 1)).matches("[\\+\\-\\*\\/\\(]{1}"))) {
  227. string += "0.";
  228. editText.setText(string);
  229. pointFlat = false;
  230. } else {
  231. string += ".";
  232. editText.setText(string);
  233. pointFlat = false;
  234. }
  235. }
  236. }
  237. if (view.getId() == R.id.button_equal) {
  238. String temp;
  239. if(string.equals("")){
  240. }else {
  241. isResult = true;
  242. string = temp = Equal(string);
  243. if (string.equals("Error")) {
  244. editText.setText("Error");
  245. left = right = 0;
  246. pointFlat = true;
  247. }else if (string.matches("^[+-]?[1-9]\\d*$") || string.matches("^[+-]?\\d+(\\.\\d+)$")
  248. || string.equals("0")){
  249. editText.setText(temp + "\n" + "= " + string);
  250. pointFlat = true;
  251. left = right = 0;
  252. } else {
  253. string = Deal(string);//中缀表达式转后缀表达式
  254. string = Calculate(string);
  255. editText.setText(temp + "\n" + "= " + string);
  256. left = right = 0;
  257. isResult = true;
  258. pointFlat = true;
  259. }
  260. }
  261. }
  262. }

 处理输入的表达式

        这个函数是处理一些不完整的输入比如少括号、小数点后没有数值、表达式前后是计算符号等等,以提高该计算器的鲁棒性

  1. public String Equal(String string){
  2. int length_equ = string.length();
  3. if(length_equ == 1 && (string.equals("(") || string.equals(")"))){
  4. string = "Error";
  5. return string;
  6. }else if (String.valueOf(string.charAt(0)).equals(")")){
  7. string = "Error";
  8. return string;
  9. }
  10. if (length_equ == 2 && string.equals("()")){
  11. string = "Error";
  12. return string;
  13. }
  14. if (length_equ - 1 >= 0 && String.valueOf(string.charAt(length_equ - 1)).matches("[\\*\\/]{1}")){
  15. string += "1";
  16. } else if (length_equ - 1 >= 0 && String.valueOf(string.charAt(length_equ - 1)).matches("[\\+\\-\\.]{1}")) {
  17. string += "0";
  18. }//结尾是运算符的情况
  19. if (String.valueOf(string.charAt(0)).matches("[\\+\\-\\*\\/]{1}")){
  20. string = "0" + string;
  21. } //开头是运算符的情况
  22. while(left != right){
  23. if (left > right){
  24. right++;
  25. string += ")";
  26. }else if(left < right){
  27. string = "Error";
  28. return string;
  29. }
  30. }//括号不匹配的情况
  31. for (int i = 0; i < string.length(); i++) {
  32. String temp = String.valueOf(string.charAt(i));
  33. if (temp.equals("(") && i + 1 < string.length()
  34. && String.valueOf(string.charAt(i + 1)).matches("[\\+\\*\\/\\)]{1}")) {
  35. string = "Error";
  36. break;
  37. } else if (temp.equals(")") && i - 1 >= 0 &&
  38. String.valueOf(string.charAt(i - 1)).matches("[\\+\\-\\*\\/\\(]{1}")) {
  39. string = "Error";
  40. break;
  41. } //出现(+*/ 或者 +-*/)的情况
  42. if (temp.equals("(") && i - 1 > 0
  43. && String.valueOf(string.charAt(i - 1)).matches("[0-9\\.\\)]{1}")) {
  44. string = "Error";
  45. break;
  46. } else if (temp.equals(")") && i + 1 < string.length()
  47. && String.valueOf(string.charAt(i + 1)).matches("[0-9\\(\\.\\(]{1}")) {
  48. string = "Error";
  49. break;
  50. }//防止出现[0-9]( 和 )[0-9]的情况
  51. }
  52. if (string.length() >= 2 && string.charAt(0) == '(' && string.charAt(string.length() - 1) == ')'){
  53. String temp = string.substring(1,string.length() - 1);
  54. if (temp.matches("^[+-]?[1-9]\\d*$") || temp.matches("^[+-]?\\d+(\\.\\d+)$")
  55. || temp.equals("0")){
  56. return temp;
  57. }
  58. }
  59. return string;
  60. }

中缀转后缀的函数

        中缀转后缀是实现该计算器的核心算法,没学过的建议先去补一下该方面的知识

        中缀表达式转后缀表达式

  1. public String Deal(String infix){
  2. Stack<String> stack = new Stack<>();
  3. StringBuilder postfix = new StringBuilder();
  4. int length = infix.length();
  5. for (int i = 0; i < length; i++){
  6. String temp;
  7. String charAt = String.valueOf(infix.charAt(i));
  8. if (charAt.equals("(")){
  9. stack.push(String.valueOf(charAt));
  10. } else if (charAt.equals("+") || charAt.equals("-")) {
  11. while (!stack.isEmpty()){
  12. temp = stack.peek();
  13. if (temp.equals("(")){
  14. break;
  15. }
  16. postfix.append(" ").append(stack.pop());
  17. }
  18. stack.push(charAt);
  19. } else if (charAt.equals("*") || charAt.equals("/")) {
  20. while (!stack.isEmpty()){
  21. temp = stack.pop();
  22. if (temp.equals("(") || temp.equals("+") || temp.equals("-")){
  23. stack.push(temp);
  24. break;
  25. }
  26. postfix.append(" ").append(temp);
  27. }
  28. stack.push(charAt);
  29. } else if (charAt.equals(")")) {
  30. while (!stack.isEmpty()){
  31. temp = stack.pop();
  32. if (!temp.equals("(")){
  33. postfix.append(" ").append(temp);
  34. }else {
  35. break;
  36. }
  37. }
  38. } else if (charAt.matches("[0-9]|\\.")){
  39. postfix.append(" ").append(charAt);
  40. if (i < length - 1){
  41. int j = i + 1;
  42. String nextNumber = String.valueOf(infix.charAt(j));
  43. while (j < length && nextNumber.matches("[0-9]|\\.")){
  44. postfix.append(nextNumber);
  45. if (++j < length)
  46. nextNumber = String.valueOf(infix.charAt(j));
  47. }
  48. i = j - 1;
  49. }
  50. }
  51. }
  52. while (!stack.isEmpty()){
  53. postfix.append(" ").append(stack.pop());
  54. }
  55. return postfix.toString().trim();
  56. }

计算函数

        处理完输入的字符串接下来就是计算了,这里全程使用Bigdecimal,在除法处使用了double,因为Bigdecimal精度是十分准确的,在计算无限小数时无法输出会报错,除非设置四舍五入,但是精度的话无法控制得很好,所以我结合两者一起使用

  1. public String Calculate(@NonNull String s){
  2. String[] nums = s.split(" ");
  3. Stack<String> stack = new Stack<>();
  4. BigDecimal big1,big2,big;
  5. String result = "";
  6. for(String str : nums){
  7. if (str.matches("^[+-]?[1-9]\\d*$") || str.matches("^[+-]?\\d+(\\.\\d+)$") || str.equals("0")){
  8. stack.push(str);
  9. } else if (str.equals("+")){
  10. big1 = new BigDecimal(stack.pop());
  11. big2 = new BigDecimal(stack.pop());
  12. big = big2.add(big1);
  13. result = big + "";
  14. stack.push(result);
  15. } else if (str.equals("-")) {
  16. big1 = new BigDecimal(stack.pop());
  17. big2 = new BigDecimal(stack.pop());
  18. big = big2.subtract(big1);
  19. result = big + "";
  20. stack.push(result);
  21. } else if (str.equals("*")) {
  22. big1 = new BigDecimal(stack.pop());
  23. big2 = new BigDecimal(stack.pop());
  24. big = big2.multiply(big1);
  25. result = big + "";
  26. stack.push(result);
  27. } else if (str.equals("/")) {
  28. String temp1 = stack.pop();
  29. String temp2 = stack.pop();
  30. big1 = new BigDecimal(temp1);
  31. big2 = new BigDecimal(temp2);
  32. double b1 = Double.valueOf(temp1);
  33. double b2 = Double.valueOf(temp2);
  34. if (big1.compareTo(BigDecimal.ZERO) == 0){
  35. return "Error : 除数不能为0";
  36. }
  37. if (temp1.length() <= 20 && temp2.length() <= 20){
  38. double b = b2 / b1;
  39. result = b + "";
  40. }else {
  41. big = big2.divide(big1,BigDecimal.ROUND_HALF_UP);
  42. result = new BigDecimal(big + "").setScale(12, RoundingMode.HALF_UP) + "";
  43. }
  44. stack.push(result);
  45. } else {
  46. return "Error : " + str + "不是数字";
  47. }
  48. }
  49. return result;
  50. }

效果图

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/223245
推荐阅读
相关标签
  

闽ICP备14008679号