Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- import java.util.StringTokenizer;
- public class EquationSolver extends JFrame
- implements ActionListener
- {
- private JTextField display;
- private static final String ARROW = "==> ";
- public EquationSolver()
- {
- super("Equation Solver");
- display = new JTextField(40);
- display.setFont(new Font("Monospaced", Font.BOLD, 14));
- display.setBackground(Color.white);
- display.setForeground(Color.blue);
- display.addActionListener(this);
- display.setText("Enter a math problem to solve");
- setBounds(50, 150, 450, 100);
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- Container c = getContentPane();
- c.setLayout(new FlowLayout());
- c.add(display);
- setVisible(true);
- // Select the whole display text:
- display.selectAll();
- // Prepare for typing:
- display.requestFocus();
- }
- public void actionPerformed(ActionEvent e)
- {
- // Skip if display has any selected text:
- if (display.getSelectedText() != null)
- return;
- String text = display.getText();
- display.setText(text + " " + process(text));
- display.selectAll();
- }
- private String process(String s)
- {
- String term1, op, term2;
- s = s.trim();
- for(int i=0;i<s.length();i++)
- {
- char x=s.charAt(i);
- if (x=='+' || x=='-' || x=='*' || x=='/' || x=='%')
- {
- int r=s.indexOf('x');
- String q=s.substring(0,r);
- String y=s.substring(r+1,s.length());
- s = q+" "+x+" "+y;
- break;
- }
- }
- StringTokenizer terms = new StringTokenizer(s);
- if (terms.countTokens() == 3)
- {
- term1 = terms.nextToken();
- op = terms.nextToken();
- term2 = terms.nextToken();
- return evaluate(term1, op, term2);
- }
- else
- return ARROW + "Syntax error";
- }
- /**
- * Evaluates an arithmetic expression in the form
- * "a +/- b" and returns the result
- * in the form "= c" or an error message.
- */
- private String evaluate(String term1, String op, String term2)
- {
- String result;
- if (op.length() != 1)
- return ARROW + "Syntax error";
- char opSign = op.charAt(0);
- int a = Integer.parseInt(term1);
- int b = Integer.parseInt(term2);
- switch (opSign)
- {
- case '+':
- result = "= " + (a + b);
- break;
- case '-':
- result = "= " + (a - b);
- break;
- case '*':
- result = "= "+(a*b);
- break;
- case '/':
- if(b!=0 && a%b==0)
- result = "= "+(a/b);
- else if(b==0)
- return ARROW + " Divide by zero error!";
- else
- return ARROW + " "+a+" is not evenly divisible by "+b;
- break;
- case '%':
- if (b!=0)
- result = "= "+(a%b);
- else
- return ARROW + " Divide by zero error!";
- break;
- default:
- result = ARROW + "Invalid operation";
- break;
- }
- return result;
- }
- public static void main(String args[])
- {
- EquationSolver panel = new EquationSolver();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement