View Single Post
Join Date: Jul 2008
Posts: 5
Reputation: ocreds has a little shameless behaviour in the past 
Solved Threads: 0
ocreds ocreds is offline Offline
Newbie Poster

Guys I Need help about explaining the code of this PEMDAS calculator.

 
0
  #1
Sep 13th, 2008
I find it difficult in this java programming language that's why I need your help to defend this code in my class.

I got this code from internet with comments and explanation. but there are some codes and explanation that I don't understand.




  1.  
  2. /* Read me:
  3.  Note: As I have said this program has already comments.
  4.   If you see this "==" sign in a comment like this "//==",
  5.   it means that is my question.
  6. *------------------------------------------------------------------------------/
  7.  
  8.  
  9.  
  10. /*
  11.   This module contains the recursive descent
  12.   parser that does not use variables.
  13. */
  14.  
  15. // Exception class for parser errors.
  16. class ParserException extends Exception {
  17. String errStr; // describes the error
  18.  
  19.  
  20. public ParserException(String str) {
  21. errStr = str;
  22. }
  23.  
  24. public String toString() {
  25. return errStr;
  26. }
  27. }
  28.  
  29. class Parser { //==what is the concept of parser?
  30. // These are the token types.
  31. final int NONE = 0; //== why NONE is initially zero
  32. final int DELIMITER = 1; //== why DELIMITER is initially to 1
  33. final int VARIABLE = 2; //== what is purpose of these token type
  34. final int NUMBER = 3;
  35.  
  36. // These are the types of syntax errors.
  37. final int SYNTAX = 0;
  38. final int UNBALPARENS = 1;
  39. final int NOEXP = 2;
  40. final int DIVBYZERO = 3;
  41.  
  42. // This token indicates end-of-expression.
  43. final String EOE = "\0"; //== purpose of this and why "\0"?
  44. //== Can you explain what is end-of-expression.
  45.  
  46. //== What is exp, expIndx, token and toktype and its purpose
  47. private String exp; // refers to expression string
  48. private int expIdx; // current index into the expression
  49. private String token; // holds current token
  50. private int tokType; // holds token's type
  51.  
  52. // Parser entry point.
  53. public double evaluate(String expstr) throws ParserException
  54. {
  55. double result;
  56. exp = expstr;
  57. expIdx = 0;
  58.  
  59.  
  60. getToken();
  61. if(token.equals(EOE))
  62. handleErr(NOEXP); // no expression present
  63.  
  64. // Parse and evaluate the expression.
  65. result = evalExp2(); //== What is parse? and why result is equals to evalExp2
  66.  
  67. if(!token.equals(EOE)) // last token must be EOE //== Meaning of this
  68. handleErr(SYNTAX); //== Why we throw to SYNTAX
  69.  
  70. return result; //== Why we return to result
  71. }
  72.  
  73. // Add or subtract two terms.
  74. private double evalExp2() throws ParserException
  75. {
  76. char op;
  77. double result; //== why we have so many result declaration
  78. double partialResult; //== purpose of this, Why we have this?
  79.  
  80. result = evalExp3(); //== purpose of evalExp3
  81.  
  82.  
  83. //== Meaning of chartAt(0)
  84. while((op = token.charAt(0)) == '+' || op == '-') {
  85. getToken();
  86. partialResult = evalExp3(); //==why do we need to declare partialResult is equals to evalExp3?
  87. switch(op) { //== meaning of switch adn why we switch op?
  88. case '-':
  89. result = result - partialResult;
  90. break;
  91. case '+':
  92. result = result + partialResult;
  93. break;
  94. }
  95. }
  96. return result;
  97. }
  98.  
  99. // Multiply or divide two factors.
  100. private double evalExp3() throws ParserException
  101. {
  102. char op;
  103. double result;
  104. double partialResult;
  105.  
  106. result = evalExp4();
  107.  
  108. while((op = token.charAt(0)) == '*' ||
  109. op == '/' || op == '%') {
  110. getToken();
  111. partialResult = evalExp4();
  112. switch(op) {
  113. case '*':
  114. result = result * partialResult;
  115. break;
  116. case '/':
  117. if(partialResult == 0.0)
  118. handleErr(DIVBYZERO);
  119. result = result / partialResult;
  120. break;
  121. case '%':
  122. if(partialResult == 0.0)
  123. handleErr(DIVBYZERO);
  124. result = result % partialResult;
  125. break;
  126. }
  127. }
  128. return result;
  129. }
  130.  
  131. // Process an exponent.
  132. private double evalExp4() throws ParserException
  133. {
  134. double result;
  135. double partialResult;
  136. double ex;
  137. int t;
  138.  
  139. result = evalExp5();
  140.  
  141. if(token.equals("^")) { //== Pls elaborate this exponent
  142. getToken();
  143. partialResult = evalExp4();
  144. ex = result; //== What we have ex
  145. if(partialResult == 0.0) {
  146. result = 1.0;
  147. } else
  148. for(t=(int)partialResult-1; t > 0; t--) //== especially this one
  149. //== why t-1 and t--
  150. result = result * ex;
  151. }
  152. return result;
  153. }
  154.  
  155. // Evaluate a unary + or -.
  156. private double evalExp5() throws ParserException
  157. {
  158. double result;
  159. String op;
  160.  
  161. op = "";
  162. if((tokType == DELIMITER) &&
  163. token.equals("+") || token.equals("-")) {
  164. op = token;
  165. getToken();
  166.  
  167. }
  168. result = evalExp6();
  169.  
  170. if(op.equals("-")) result = -result;
  171.  
  172. return result;
  173. }
  174.  
  175. // Process a parenthesized expression.
  176. private double evalExp6() throws ParserException
  177. {
  178. double result;
  179.  
  180. if(token.equals("(")) {
  181. getToken();
  182. result = evalExp2();
  183. if(!token.equals(")"))
  184. handleErr(UNBALPARENS);
  185. getToken();
  186. }
  187. else result = atom();
  188.  
  189. return result;
  190. }
  191.  
  192. // Get the value of a number.
  193. private double atom() throws ParserException
  194. {
  195. double result;
  196.  
  197. switch(tokType) {
  198. case NUMBER:
  199. try { // What is try command
  200. result = Double.parseDouble(token);
  201. } catch (NumberFormatException exc) { // What happen in this line
  202. handleErr(SYNTAX);
  203. }
  204. getToken();
  205. break;
  206. default:
  207. handleErr(SYNTAX);
  208. break;
  209. }
  210. return result;
  211. }
  212.  
  213. // Handle an error.
  214. private void handleErr(int error) throws ParserException
  215. {
  216. String[] err = {"Syntax Error","Unbalanced Parenthesesa","No Expression Present","Division by Zero"
  217. };
  218.  
  219. throw new ParserException(err[error]);
  220. }
  221.  
  222. // Obtain the next token.
  223. private void getToken()
  224. {
  225. tokType = NONE;
  226. token = "";
  227.  
  228. // Check for end of expression.
  229. if(expIdx == exp.length()) {
  230. token = EOE;
  231. return;
  232. }
  233.  
  234. // Skip over white space.
  235. while(expIdx < exp.length() &&
  236. Character.isWhitespace(exp.charAt(expIdx))) ++expIdx;
  237.  
  238. // Trailing whitespace ends expression.
  239. if(expIdx == exp.length()) {
  240. token = EOE;
  241. return;
  242. }
  243.  
  244. if(isDelim(exp.charAt(expIdx))) { // is operator
  245. token += exp.charAt(expIdx);
  246. expIdx++;
  247. tokType = DELIMITER;
  248. }
  249. else if(Character.isLetter(exp.charAt(expIdx))) { // is variable
  250. while(!isDelim(exp.charAt(expIdx))) {
  251. token += exp.charAt(expIdx);
  252. expIdx++;
  253. if(expIdx >= exp.length()) break;
  254. }
  255. tokType = VARIABLE;
  256. }
  257. else if(Character.isDigit(exp.charAt(expIdx))) { // is number
  258. while(!isDelim(exp.charAt(expIdx))) {
  259. token += exp.charAt(expIdx);
  260. expIdx++;
  261. if(expIdx >= exp.length()) break; //== why we use break
  262. }
  263. tokType = NUMBER;
  264. }
  265. else { // unknown character terminates expression
  266. token = EOE;
  267. return;
  268. }
  269. }
  270.  
  271. // Return true if c is a delimiter.
  272. private boolean isDelim(char c) //== why we have char c
  273. {
  274. if((" +-/*%^=()".indexOf(c) != -1)) //== Meaning of this line, why != -1?
  275. return true; //== Why return to true
  276. return false;
  277. }
  278.  
  279. }
  280.  
  281.  
  282. /*== If you think I missed something in my questions that so important please let me know what it is and explain what you mean.
  283.  
  284.  
  285. Thanks for reading....
  286. */
Here's the link of explanation that I don't fully understand.

http://www.usaupload.net/d/yfxpm4fwp3x

---------------------------------------------------------------------------------------------------------

  1.  
  2.  
  3.  
  4. import javax.swing.*;
  5. import java.awt.event.*;
  6. import java.awt.*;
  7.  
  8.  
  9. public class cal {
  10.  
  11. JLabel expression1 = new JLabel("Expression:");
  12. JLabel result1 = new JLabel("Result: ");
  13.  
  14.  
  15. JTextField expression_textf1 = new JTextField(22);
  16. JTextField result_textf1 = new JTextField(10);
  17.  
  18.  
  19. JButton clear1 = new JButton(" Clear ");
  20.  
  21.  
  22.  
  23.  
  24.  
  25. JButton calculate1 = new JButton(" Calculate");
  26. JButton cancel1 = new JButton(" Cancel");
  27.  
  28. Parser p = new Parser();
  29.  
  30. public JPanel gui_2() {
  31.  
  32. JPanel northPanel1 = new JPanel();
  33. JPanel northPanel2 = new JPanel();
  34.  
  35. northPanel1.setLayout(new GridLayout(2, 0));
  36.  
  37. northPanel1.add(expression1);
  38. northPanel1.add(expression_textf1);
  39. northPanel1.add(result1);
  40. northPanel1.add(result_textf1);
  41.  
  42. northPanel2.setLayout(new FlowLayout(FlowLayout.CENTER));
  43. northPanel2.add(northPanel1);
  44.  
  45. return northPanel2;
  46.  
  47. }
  48.  
  49. public JPanel gui_3() {
  50.  
  51.  
  52. JPanel southPanel1 = new JPanel();
  53. JPanel southPanel2 = new JPanel();
  54.  
  55. southPanel1.setLayout(new GridLayout(2, 2));
  56.  
  57.  
  58. southPanel2.add(calculate1);
  59. southPanel2.add(clear1);
  60. southPanel2.add(cancel1);
  61.  
  62. result_textf1.setEditable(false); // Result field should not be editable
  63.  
  64. calculate1.addActionListener(new ActionListener() {
  65. public void actionPerformed(ActionEvent e) {
  66. String expr = expression_textf1.getText().trim();
  67. try {
  68. result_textf1.setText(String.valueOf(p.evaluate(expr)));
  69. }
  70. catch(ParserException exc) {
  71. result_textf1.setText(String.valueOf(exc));
  72. }
  73. }
  74. });
  75.  
  76. clear1.addActionListener(new ActionListener() {
  77. public void actionPerformed(ActionEvent e) {
  78. expression_textf1.setText("");
  79. result_textf1.setText("");
  80. expression_textf1.requestFocus();
  81. }
  82. });
  83.  
  84. cancel1.addActionListener(new ActionListener() {
  85. public void actionPerformed(ActionEvent e) {
  86. System.exit(0);
  87. }
  88. });
  89.  
  90. southPanel2.setLayout(new FlowLayout(FlowLayout.CENTER));
  91. southPanel2.add(southPanel1);
  92.  
  93. return southPanel2;
  94.  
  95. }
  96.  
  97.  
  98. public JFrame buildNewFrame() {
  99.  
  100. try{
  101. UIManager.setLookAndFeel(
  102. UIManager.getSystemLookAndFeelClassName());
  103.  
  104.  
  105. }catch(Exception e){}
  106.  
  107. cal re = new cal();
  108.  
  109. JPanel northPanel = new JPanel();
  110. JPanel southPanel = new JPanel();
  111. JPanel finalPanel = new JPanel();
  112.  
  113. northPanel = re.gui_2 ();
  114. southPanel = re.gui_3 ();
  115.  
  116.  
  117. finalPanel.setLayout( new BorderLayout());
  118. finalPanel.add(northPanel, BorderLayout.NORTH);
  119. finalPanel.add(southPanel, BorderLayout.SOUTH);
  120.  
  121.  
  122. JFrame frame = new JFrame("Calculator");
  123.  
  124. frame.setSize(900, 900);
  125.  
  126. frame.getContentPane().add(finalPanel);
  127.  
  128. frame.addWindowListener( new WindowAdapter()
  129.  
  130.  
  131.  
  132.  
  133.  
  134. {
  135.  
  136. public void windowClosing( WindowEvent e) {
  137.  
  138. System.exit(0);
  139. }
  140. });
  141.  
  142.  
  143. return frame;
  144.  
  145.  
  146. }
  147.  
  148. }

And lastly the runner.


  1.  
  2.  
  3.  
  4.  
  5. import javax.swing.JFrame;
  6.  
  7. public class runner {
  8.  
  9. public static void main(String args[]){
  10.  
  11. JFrame lor = new JFrame();
  12. cal rece = new cal();
  13. lor = rece.buildNewFrame();
  14.  
  15. lor.pack();
  16. lor.setVisible(true);
  17.  
  18. }
  19.  
  20. }
Reply With Quote