Calculate.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package com.hcks.cmfds.util;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. public class Calculate {
  5. public static void main(String[] args) {
  6. String s="((66.0)*(744.0)-(175.0))/((66.0)*(744.0))";
  7. s.replace(",", " ");
  8. Calculate c=new Calculate(s);
  9. Object o=c.DoCal();
  10. System.out.print(o);
  11. }
  12. // ������ջ
  13. private List<Object> HList;
  14. // ��ֵջ
  15. public List<Object> Vlist;
  16. // �����Թ���
  17. private CalUtility cu;
  18. // �������������
  19. private OperFactory factory;
  20. public Calculate(String str)
  21. {
  22. str=str.replace("(-", "(0-");
  23. HList=new ArrayList<Object>();
  24. Vlist=new ArrayList<Object>();
  25. cu=new CalUtility(str);
  26. factory=new OperFactory();
  27. }
  28. //����
  29. public Object DoCal()
  30. {
  31. String strTmp=cu.getItem();
  32. while(true)
  33. {
  34. if(cu.isNum(strTmp))
  35. {
  36. //�������ֵ����д�����ջ
  37. Vlist.add(strTmp);
  38. }
  39. else
  40. {
  41. //�����
  42. Cal(strTmp);
  43. }
  44. if(strTmp.equals(""))
  45. break;
  46. strTmp=cu.getItem();
  47. }
  48. return Vlist.get(0);
  49. }
  50. //�����
  51. private void Cal(String str)
  52. {
  53. //��ű�Ϊ�գ����ҵ�ǰ���Ϊ""������Ϊ�Ѿ��������
  54. if(str.equals("") && HList.size()==0 )
  55. {
  56. return;
  57. }
  58. if(HList.size()>0)
  59. {
  60. if(HList.get(HList.size()-1).toString().equals("(") && str.equals(")"))
  61. {
  62. HList.remove(HList.size()-1);
  63. if(HList.size()>0)
  64. {
  65. str=HList.get(HList.size()-1).toString();
  66. HList.remove(HList.size()-1);
  67. Cal(str);
  68. }
  69. return;
  70. }
  71. else if(cu.compare(HList.get(HList.size()-1).toString(),str) && !str.equals("("))
  72. {
  73. //������ȣ������
  74. IOper p=factory.CreateOper(HList.get(HList.size()-1).toString());
  75. if(p!=null)
  76. {
  77. Vlist.set(Vlist.size()-2, p.oper(Vlist.get(Vlist.size()-2), Vlist.get(Vlist.size()-1)));
  78. HList.remove(HList.size()-1);
  79. Vlist.remove(Vlist.size()-1);
  80. Cal(str);
  81. }
  82. }
  83. else if(!str.equals(""))
  84. HList.add(str);
  85. }
  86. else
  87. {
  88. if(!str.equals(""))
  89. HList.add(str);
  90. }
  91. }
  92. }