Somebody help me, i'm a beginners of the java language, but in my interested to learn a java. and I create a GUI but the MDAS formula is not there, it because i dont know how to solve that, it cause need a pop and post function for the Calculator program.

///runner.java



import javax.swing.JFrame;


public class runner {


public static void main(String args[]){


JFrame lor = new JFrame();
cal rece = new cal();
lor = rece.buildNewFrame();


lor.pack();
lor.setVisible(true);


}


}


/////cal.java


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;



public class cal {


JLabel expression1  = new JLabel("Expression:");
JLabel result1  = new JLabel("Result: ");



JTextField expression_textf1 = new JTextField(30);
JTextField result_textf1 = new JTextField(10);



JButton clear1 = new JButton(" Clear ");


JButton calculate1 = new JButton(" Calculate");
JButton cancel1 = new JButton(" Cancel");


public JPanel gui_2() {


JPanel northPanel1 = new JPanel();
JPanel northPanel2 = new JPanel();


northPanel1.setLayout(new GridLayout(2, 0));


northPanel1.add(expression1);
northPanel1.add(expression_textf1);
northPanel1.add(result1);
northPanel1.add(result_textf1);


northPanel2.setLayout(new FlowLayout(FlowLayout.CENTER));
northPanel2.add(northPanel1);


return northPanel2;


}


public JPanel gui_3() {



JPanel southPanel1 = new JPanel();
JPanel southPanel2 = new JPanel();


southPanel1.setLayout(new GridLayout(2, 2));



southPanel2.add(calculate1);
southPanel2.add(clear1);
southPanel2.add(cancel1);



southPanel2.setLayout(new FlowLayout(FlowLayout.CENTER));
southPanel2.add(southPanel1);


return southPanel2;


}



public JFrame buildNewFrame() {


try{
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());



}catch(Exception e){}


cal re = new cal();


JPanel northPanel = new JPanel();
JPanel southPanel = new JPanel();
JPanel finalPanel = new JPanel();


northPanel = re.gui_2 ();
southPanel = re.gui_3 ();



finalPanel.setLayout( new BorderLayout());
finalPanel.add(northPanel, BorderLayout.NORTH);
finalPanel.add(southPanel, BorderLayout.SOUTH);



JFrame frame = new JFrame("CALCULATOR IN PRELIM DEPENDS");


frame.setSize(900, 900);


frame.getContentPane().add(finalPanel);


frame.addWindowListener( new WindowAdapter()


{


public void windowClosing( WindowEvent e) {


System.exit(0);
}
});



return frame;


}


}

please use code tags [*code=java*][*/code*] without the asterisks (*)

what is you problem, actually making it calculate? if so, i have a thread on the subject, that has a solution at the end: here
the second page has the answer to that.

personal preference maybe, but i don't like the way you set up your frame, with the method in another class that sets up a frame for a different class, seems a little... indirect and convoluted...

but...

nothing actually wrong with it, code-wise

Somebody help me, i'm a beginners of the java language, but in my interested to learn a java. and I create a GUI but the MDAS formula is not there, it because i dont know how to solve that, it cause need a pop and post function for the Calculator program.

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class Calculator extends JFrame {
	
	private JLabel statusLabel;
	private JTextField inputField;
	private JButton calculate, clear, cancel;

	

	
	
	
	public Calculator()
	
	{
		
		super("Calculator in Preliminary depends using a MDAS and PEMDAS rules");
		
		
		Container container= getContentPane();
		container.setLayout(new FlowLayout());
		
		
		statusLabel = new JLabel();
	
		
		container.add(new JLabel("Expression: "));
		inputField = new JTextField (20);
		container.add(inputField);
		
        container.add(new JLabel("Result: "));
		inputField = new JTextField (10);
		container.add(inputField);
				
		
		// button for  Expression


		calculate = new JButton();	
		JButton calculate = new JButton("Calculate");
		container.add(calculate);
				
		clear = new JButton();
		JButton clear = new JButton("Clear");	
		container.add(clear);
		
		cancel = new JButton();
		JButton cancel = new JButton("Cancel");	
		container.add(cancel);	
			
      

			container.add( statusLabel );
			
			setSize( 500, 150 );
			setVisible( true );
			
			}
	
	public static void main (String args[])
	
	{
		
		Calculator application = new Calculator();
		application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
			
	
	}

////////////

hi, this is my final code for my project. somebody help me. i want to learn a step by step coding of calculator,

/*   
   This module contains the recursive descent  
   parser that uses variables.  
 */

// Exception class for parser errors.  
class ParserException extends Exception {
	String errStr; // describes the error 

	public ParserException(String str) {
		errStr = str;
	}

	public String toString() {
		return errStr;
	}
}

public class Parser {
	// These are the token types. 
	final int NONE = 0;
	final int DELIMITER = 1;
	final int VARIABLE = 2;
	final int NUMBER = 3;

	// These are the types of syntax errors. 
	final int SYNTAX = 0;
	final int UNBALPARENS = 1;
	final int NOEXP = 2;
	final int DIVBYZERO = 3;

	// This token indicates end-of-expression. 
	final String EOE = "\0";

	private String exp; // refers to expression string  
	private int expIdx; // current index into the expression  
	private String token; // holds current token  
	private int tokType; // holds token's type  

	// Array for variables.  
	private double vars[] = new double[26];

	// Parser entry point.  
	public double evaluate(String expstr) throws ParserException {
		double result;
		exp = expstr;
		expIdx = 0;

		getToken();
		if (token.equals(EOE))
			handleErr(NOEXP); // no expression present  

		// Parse and evaluate the expression. 
		result = evalExp1();

		if (!token.equals(EOE)) // last token must be EOE  
			handleErr(SYNTAX);

		return result;
	}

	// Process an assignment.  
	private double evalExp1() throws ParserException {
		double result;
		int varIdx;
		int ttokType;
		String temptoken;

		if (tokType == VARIABLE) {
			// save old token  
			temptoken = new String(token);
			ttokType = tokType;

			// Compute the index of the variable.  
			varIdx = Character.toUpperCase(token.charAt(0)) - 'A';

			getToken();
			if (!token.equals("=")) {
				putBack(); // return current token  
				// restore old token -- not an assignment  
				token = new String(temptoken);
				tokType = ttokType;
			}
			else {
				getToken(); // get next part of exp  
				result = evalExp2();
				vars[varIdx] = result;
				return result;
			}
		}

		return evalExp2();
	}

	// Add or subtract two terms.  
	private double evalExp2() throws ParserException {
		char op;
		double result;
		double partialResult;

		result = evalExp3();

		while ((op = token.charAt(0)) == '+' || op == '-') {
			getToken();
			partialResult = evalExp3();
			switch (op) {
				case '-':
					result = result - partialResult;
					break;
				case '+':
					result = result + partialResult;
					break;
			}
		}
		return result;
	}

	// Multiply or divide two factors.  
	private double evalExp3() throws ParserException {
		char op;
		double result;
		double partialResult;

		result = evalExp4();

		while ((op = token.charAt(0)) == '*' || op == '/' || op == '%') {
			getToken();
			partialResult = evalExp4();
			switch (op) {
				case '*':
					result = result * partialResult;
					break;
				case '/':
					if (partialResult == 0.0)
						handleErr(DIVBYZERO);
					result = result / partialResult;
					break;
				case '%':
					if (partialResult == 0.0)
						handleErr(DIVBYZERO);
					result = result % partialResult;
					break;
			}
		}
		return result;
	}

	// Process an exponent.  
	private double evalExp4() throws ParserException {
		double result;
		double partialResult;
		double ex;
		int t;

		result = evalExp5();

		if (token.equals("^")) {
			getToken();
			partialResult = evalExp4();
			ex = result;
			if (partialResult == 0.0) {
				result = 1.0;
			}
			else
				for (t = (int) partialResult - 1; t > 0; t--)
					result = result * ex;
		}
		return result;
	}

	// Evaluate a unary + or -.  
	private double evalExp5() throws ParserException {
		double result;
		String op;

		op = "";
		if ((tokType == DELIMITER) && token.equals("+") || token.equals("-")) {
			op = token;
			getToken();
		}
		result = evalExp6();

		if (op.equals("-"))
			result = -result;

		return result;
	}

	// Process a parenthesized expression.  
	private double evalExp6() throws ParserException {
		double result;

		if (token.equals("(")) {
			getToken();
			result = evalExp2();
			if (!token.equals(")"))
				handleErr(UNBALPARENS);
			getToken();
		}
		else
			result = atom();

		return result;
	}

	// Get the value of a number or variable.  
	private double atom() throws ParserException {
		double result = 0.0;

		switch (tokType) {
			case NUMBER:
				try {
					result = Double.parseDouble(token);
				}
				catch (NumberFormatException exc) {
					handleErr(SYNTAX);
				}
				getToken();
				break;
			case VARIABLE:
				result = findVar(token);
				getToken();
				break;
			default:
				handleErr(SYNTAX);
				break;
		}
		return result;
	}

	// Return the value of a variable.  
	private double findVar(String vname) throws ParserException {
		if (!Character.isLetter(vname.charAt(0))) {
			handleErr(SYNTAX);
			return 0.0;
		}
		return vars[Character.toUpperCase(vname.charAt(0)) - 'A'];
	}

	// Return a token to the input stream.  
	private void putBack() {
		if (token == EOE)
			return;
		for (int i = 0; i < token.length(); i++)
			expIdx--;
	}

	// Handle an error.  
	private void handleErr(int error) throws ParserException {
		String[] err = { "Syntax Error", "Unbalanced Parentheses",
			"No Expression Present", "Division by Zero" };

		throw new ParserException(err[error]);
	}

	// Obtain the next token.  
	private void getToken() {
		tokType = NONE;
		token = "";

		// Check for end of expression.  
		if (expIdx == exp.length()) {
			token = EOE;
			return;
		}

		// Skip over white space. 
		while (expIdx < exp.length()
				&& Character.isWhitespace(exp.charAt(expIdx)))
			++expIdx;

		// Trailing whitespace ends expression. 
		if (expIdx == exp.length()) {
			token = EOE;
			return;
		}

		if (isDelim(exp.charAt(expIdx))) { // is operator  
			token += exp.charAt(expIdx);
			expIdx++;
			tokType = DELIMITER;
		}
		else
			if (Character.isLetter(exp.charAt(expIdx))) { // is variable  
				while (!isDelim(exp.charAt(expIdx))) {
					token += exp.charAt(expIdx);
					expIdx++;
					if (expIdx >= exp.length())
						break;
				}
				tokType = VARIABLE;
			}
			else
				if (Character.isDigit(exp.charAt(expIdx))) { // is number  
					while (!isDelim(exp.charAt(expIdx))) {
						token += exp.charAt(expIdx);
						expIdx++;
						if (expIdx >= exp.length())
							break;
					}
					tokType = NUMBER;
				}
				else { // unknown character terminates expression 
					token = EOE;
					return;
				}
	}

	// Return true if c is a delimiter.  
	private boolean isDelim(char c) {
		if ((" +-/*%^=()".indexOf(c) != -1))
			return true;
		return false;
	}
}
Parser p = new Parser();
double val = p.evaluate("2+2")

why did you PM me?

Sorry for the Dis advantage that I do for you. I PM u it because i need you help for the Java Program, It cause I'm a first timer for Java language.

Thanks for your share a code like this I try to make my best that can I understand and Apply these for my MDAS and PEMDAS calculator project.

this is PEMDAS, and i got it from this book, it's kind of an advaced book, but it is interesting.

hi, sciwizeh. thanks again that you can share your code, but i have problem, How can I insert your code in my GUI using a JFrame?

when I'm try to compile you code it's running but when I insert your code in my GUI JFrame. I have a problem to solve. I don't know how can i do these. please help me.

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class ParserException extends Exception {
String errStr; // describes the error
public ParserException(String str) {
errStr = str;
}
public String toString() {
return errStr;
}
}
public class Calculator extends JFrame {
// These are the token types.
final int NONE = 0;
final int DELIMITER = 1;
final int VARIABLE = 2;
final int NUMBER = 3;
// These are the types of syntax errors.
final int SYNTAX = 0;
final int UNBALPARENS = 1;
final int NOEXP = 2;
final int DIVBYZERO = 3;
// This token indicates end-of-expression.
final String EOE = "\0";
private String exp; // refers to expression string
private int expIdx; // current index into the expression
private String token; // holds current token
private int tokType; // holds token's type
// Array for variables.
private double vars[] = new double[26];

private JLabel statusLabel;
private JTextField inputField, resultField;
private JButton calculate, clear, cancel, infix, prefix, postfix, calcButton;
private int Exp1;
public Calculator()
{
super("Calculator in  MDAS and PEMDAS rules and Infix-postfix,  Infix-prefix rules.");

Container container= getContentPane();
container.setLayout(new FlowLayout());

statusLabel = new JLabel();

container.add(new JLabel("Expression: "));
inputField = new JTextField (20);
container.add(inputField);
container.add(new JLabel("Result: "));
resultField = new JTextField (10);
container.add(resultField);

//button for  Expression

calculate = new JButton();
JButton calculate = new JButton("Calculate");
container.add(calculate);

calculate.addActionListener(

new ActionListener(){

public void actionPerformed(ActionEvent event){

}

}
);

clear = new JButton();
JButton clear = new JButton("Clear");
container.add(clear);
cancel = new JButton();
JButton cancel = new JButton("Cancel");
container.add(cancel);
infix = new JButton();
JButton infix = new JButton("Infix");
container.add(infix);
prefix = new JButton();
JButton prefix = new JButton("Prefix");
container.add(prefix);
postfix = new JButton();
JButton postfix = new JButton("Postfix");
container.add(postfix);
setSize( 500, 150 );
setVisible( true );
}

private void setFields(){
Exp1=Integer.parseInt(inputField.getText());
}
public static void main (String args[])
{
Calculator application = new Calculator();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

/*
This module contains the recursive descent
parser that uses variables.
*/
// Exception class for parser errors.
class ParserException extends Exception {
String errStr; // describes the error
public ParserException(String str) {
errStr = str;
}
public String toString() {
return errStr;
}
}
public class Parser {
// These are the token types.
final int NONE = 0;
final int DELIMITER = 1;
final int VARIABLE = 2;
final int NUMBER = 3;
// These are the types of syntax errors.
final int SYNTAX = 0;
final int UNBALPARENS = 1;
final int NOEXP = 2;
final int DIVBYZERO = 3;
// This token indicates end-of-expression.
final String EOE = "\0";
private String exp; // refers to expression string
private int expIdx; // current index into the expression
private String token; // holds current token
private int tokType; // holds token's type
// Array for variables.
private double vars[] = new double[26];
// Parser entry point.
public double evaluate(String expstr) throws ParserException {
double result;
exp = expstr;
expIdx = 0;
getToken();
if (token.equals(EOE))
handleErr(NOEXP); // no expression present
// Parse and evaluate the expression.
result = evalExp1();
if (!token.equals(EOE)) // last token must be EOE
handleErr(SYNTAX);
return result;
}
// Process an assignment.
private double evalExp1() throws ParserException {
double result;
int varIdx;
int ttokType;
String temptoken;
if (tokType == VARIABLE) {
// save old token
temptoken = new String(token);
ttokType = tokType;
// Compute the index of the variable.
varIdx = Character.toUpperCase(token.charAt(0)) - 'A';
getToken();
if (!token.equals("=")) {
putBack(); // return current token
// restore old token -- not an assignment
token = new String(temptoken);
tokType = ttokType;
}
else {
getToken(); // get next part of exp
result = evalExp2();
vars[varIdx] = result;
return result;
}
}
return evalExp2();
}
// Add or subtract two terms.
private double evalExp2() throws ParserException {
char op;
double result;
double partialResult;
result = evalExp3();
while ((op = token.charAt(0)) == '+' || op == '-') {
getToken();
partialResult = evalExp3();
switch (op) {
case '-':
result = result - partialResult;
break;
case '+':
result = result + partialResult;
break;
}
}
return result;
}
// Multiply or divide two factors.
private double evalExp3() throws ParserException {
char op;
double result;
double partialResult;
result = evalExp4();
while ((op = token.charAt(0)) == '*' || op == '/' || op == '%') {
getToken();
partialResult = evalExp4();
switch (op) {
case '*':
result = result * partialResult;
break;
case '/':
if (partialResult == 0.0)
handleErr(DIVBYZERO);
result = result / partialResult;
break;
case '%':
if (partialResult == 0.0)
handleErr(DIVBYZERO);
result = result % partialResult;
break;
}
}
return result;
}
// Process an exponent.
private double evalExp4() throws ParserException {
double result;
double partialResult;
double ex;
int t;
result = evalExp5();
if (token.equals("^")) {
getToken();
partialResult = evalExp4();
ex = result;
if (partialResult == 0.0) {
result = 1.0;
}
else
for (t = (int) partialResult - 1; t > 0; t--)
result = result * ex;
}
return result;
}
// Evaluate a unary + or -.
private double evalExp5() throws ParserException {
double result;
String op;
op = "";
if ((tokType == DELIMITER) && token.equals("+") || token.equals("-")) {
op = token;
getToken();
}
result = evalExp6();
if (op.equals("-"))
result = -result;
return result;
}
// Process a parenthesized expression.
private double evalExp6() throws ParserException {
double result;
if (token.equals("(")) {
getToken();
result = evalExp2();
if (!token.equals(")"))
handleErr(UNBALPARENS);
getToken();
}
else
result = atom();
return result;
}
// Get the value of a number or variable.
private double atom() throws ParserException {
double result = 0.0;
switch (tokType) {
case NUMBER:
try {
result = Double.parseDouble(token);
}
catch (NumberFormatException exc) {
handleErr(SYNTAX);
}
getToken();
break;
case VARIABLE:
result = findVar(token);
getToken();
break;
default:
handleErr(SYNTAX);
break;
}
return result;
}
// Return the value of a variable.
private double findVar(String vname) throws ParserException {
if (!Character.isLetter(vname.charAt(0))) {
handleErr(SYNTAX);
return 0.0;
}
return vars[Character.toUpperCase(vname.charAt(0)) - 'A'];
}
// Return a token to the input stream.
private void putBack() {
if (token == EOE)
return;
for (int i = 0; i < token.length(); i++)
expIdx--;
}
// Handle an error.
private void handleErr(int error) throws ParserException {
String[] err = { "Syntax Error", "Unbalanced Parentheses",
"No Expression Present", "Division by Zero" };
throw new ParserException(err[error]);
}
// Obtain the next token.
private void getToken() {
tokType = NONE;
token = "";
// Check for end of expression.
if (expIdx == exp.length()) {
token = EOE;
return;
}
// Skip over white space.
while (expIdx < exp.length()
&& Character.isWhitespace(exp.charAt(expIdx)))
++expIdx;
// Trailing whitespace ends expression.
if (expIdx == exp.length()) {
token = EOE;
return;
}
if (isDelim(exp.charAt(expIdx))) { // is operator
token += exp.charAt(expIdx);
expIdx++;
tokType = DELIMITER;
}
else
if (Character.isLetter(exp.charAt(expIdx))) { // is variable
while (!isDelim(exp.charAt(expIdx))) {
token += exp.charAt(expIdx);
expIdx++;
if (expIdx >= exp.length())
break;
}
tokType = VARIABLE;
}
else
if (Character.isDigit(exp.charAt(expIdx))) { // is number
while (!isDelim(exp.charAt(expIdx))) {
token += exp.charAt(expIdx);
expIdx++;
if (expIdx >= exp.length())
break;
}
tokType = NUMBER;
}
else { // unknown character terminates expression
token = EOE;
return;
}
}
// Return true if c is a delimiter.
private boolean isDelim(char c) {
if ((" +-/*%^=()".indexOf(c) != -1))
return true;
return false;
}
}

please help.

write your GUI as you normally would, leave out my code, my code should be in a separate file called Parser.java.

your GUI class should have a member variable of type Parser, Parser yourName = new Parser(); , then your actionPerformed method should look something like this:

public void actionPerformed(ActionEvent e){
    String str = yourTextField.getText();
    String answerString = "";
    try{
         double answer = yourName.evaluate(str);
         answerString += answer;
    } catch (ParserException pe){
         answerString = pe.toString();
    }
    //DISPLAY ANSWER STRING IN WAY OF CHOOSING
}

write your GUI as you normally would, leave out my code, my code should be in a separate file called Parser.java.

your GUI class should have a member variable of type Parser, Parser yourName = new Parser(); , then your actionPerformed method should look something like this:

public void actionPerformed(ActionEvent e){
    String str = yourTextField.getText();
    String answerString = "";
    try{
         double answer = yourName.evaluate(str);
         answerString += answer;
    } catch (ParserException pe){
         answerString = pe.toString();
    }
    //DISPLAY ANSWER STRING IN WAY OF CHOOSING
}

you mean? my code is need to separate to your codes? ok.

but can I ask what do you mean Parser yourname = new Parser(); ? So I need to put like this Parser Calculator = new Parser()

you mean? my code is need to separate to your codes?

yes, my (the books) code should be in a separate file.

yes yourname can be any valid identifier of your choosing for utility* classes like Parser i user short, normally one letter names like p think of the Parser class as a class in like java.util.ArrayList, just something to use

just out of curiosity what IDE are you using?

What do you mean IDE? I don't what IDE can i use but i'm using Jcreator a old version of java.

I seperate my code's and your's but i can't call your code to my GUI. i use the code that given to me, but i can't call..

In order for him to use this--

public void actionPerformed(ActionEvent e){
    String str = yourTextField.getText();
    String answerString = "";
    try{
         double answer = yourName.evaluate(str);
         answerString += answer;
    } catch (ParserException pe){
         answerString = pe.toString();
    }
    //DISPLAY ANSWER STRING IN WAY OF CHOOSING
}

--he'll also need a ParserException.java file.

Either that or edit the code to respond to any exception, though it may be vague--

public void actionPerformed(ActionEvent e){
    String str = yourTextField.getText();
    String answerString = "";
    try{
         double answer = yourName.evaluate(str);
         answerString += answer;
    } catch (Exception e){
         answerString = e.toString(); // probably not what you want
    }
    //DISPLAY ANSWER STRING IN WAY OF CHOOSING
}

no, the parserexception is in the parser file, it is just not deemed public it works fine for me, what errors are you actually getting?

Thanks for some codes sharing.. I don't have enough time to solve it because my instructor want to see my program this day..


This I mean

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;



public class Calculator extends JFrame {
	
	
	private JLabel statusLabel;
	private JTextField inputField, resultField;
	private JButton calculate, clear, cancel;





	
     public Calculator()
	
	{
		
		super("Calculator in  MDAS and PEMDAS rules");
		
		
		Container container= getContentPane();
		container.setLayout(new FlowLayout());
		
		
		statusLabel = new JLabel();
	
		
		container.add(new JLabel("Expression: "));
		inputField = new JTextField (20);
		container.add(inputField);
		
        container.add(new JLabel("Result: "));
		resultField = new JTextField (10);
		container.add(resultField);
				
		
	//button for  Expression


	
		
		calculate = new JButton();	
		JButton calculate = new JButton("Calculate");
		container.add(calculate);
			
		clear = new JButton();
		JButton clear = new JButton("Clear");	
		container.add(clear);
		
		cancel = new JButton();
		JButton cancel = new JButton("Cancel");	
		container.add(cancel);	
			
		
		
		
			
			setSize( 500, 150 );
			setVisible( true );
			
			}
			
					
	
	public static void main (String args[])
	
	{
		
		Calculator application = new Calculator();
		application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
			
	
	}

This the GUI that I mean, once i run this GUI and compile.. but the problem is when i enter a expression into my GUI.. then When I click a calculate button, the expression can't move...

/*   
   This module contains the recursive descent  
   parser that uses variables.  
 */

// Exception class for parser errors.

  
class ParserException extends Exception {
	String errStr;  // describes the error 

	public ParserException(String str) {
		errStr = str;
	}

	public String toString() {
		return errStr;
	}
}



public class Parser {
	// These are the token types. 
	final int NONE = 0;
	final int DELIMITER = 1;
	final int VARIABLE = 2;
	final int NUMBER = 3;

	// These are the types of syntax errors. 
	final int SYNTAX = 0;
	final int UNBALPARENS = 1;
	final int NOEXP = 2;
	final int DIVBYZERO = 3;

	// This token indicates end-of-expression. 
	final String EOE = "\0";

	private String exp; // refers to expression string  
	private int expIdx; // current index into the expression  
	private String token; // holds current token  
	private int tokType; // holds token's type  

	// Array for variables.  
	private double vars[] = new double[26];	

	// Parser entry point.  
	public double evaluate(String expstr) throws ParserException {
		double result;
		exp = expstr;
		expIdx = 0;

		getToken();
		if (token.equals(EOE))
			handleErr(NOEXP); // no expression present  

		// Parse and evaluate the expression. 
		result = evalExp1();

		if (!token.equals(EOE)) // last token must be EOE  
			handleErr(SYNTAX);

		return result;
	}

	// Process an assignment.  
	private double evalExp1() throws ParserException {
		double result;
		int varIdx;
		int ttokType;
		String temptoken;

		if (tokType == VARIABLE) {
			// save old token  
			temptoken = new String(token);
			ttokType = tokType;

			// Compute the index of the variable.  
			varIdx = Character.toUpperCase(token.charAt(0)) - 'A';

			getToken();
			if (!token.equals("=")) {
				putBack(); // return current token  
				// restore old token -- not an assignment  
				token = new String(temptoken);
				tokType = ttokType;
			}
			else {
				getToken(); // get next part of exp  
				result = evalExp2();
				vars[varIdx] = result;
				return result;
			}
		}

		return evalExp2();
	}

	// Add or subtract two terms.  
	private double evalExp2() throws ParserException {
		char op;
		double result;
		double partialResult;

		result = evalExp3();

		while ((op = token.charAt(0)) == '+' || op == '-') {
			getToken();
			partialResult = evalExp3();
			switch (op) {
				case '-':
					result = result - partialResult;
					break;
				case '+':
					result = result + partialResult;
					break;
			}
		}
		return result;
	}

	// Multiply or divide two factors.  
	
	private double evalExp3() throws ParserException {
		char op;
		double result;
		double partialResult;

		result = evalExp4();

		while ((op = token.charAt(0)) == '*' || op == '/' || op == '%') {
			getToken();
			partialResult = evalExp4();
			switch (op) {
				case '*':
					result = result * partialResult;
					break;
				case '/':
					if (partialResult == 0.0)
						handleErr(DIVBYZERO);
					result = result / partialResult;
					break;
				case '%':
					if (partialResult == 0.0)
						handleErr(DIVBYZERO);
					result = result % partialResult;
					break;
			}
		}
		return result;
	}

	// Process an exponent.  
	private double evalExp4() throws ParserException {
		double result;
		double partialResult;
		double ex;
		int t;

		result = evalExp5();

		if (token.equals("^")) {
			getToken();
			partialResult = evalExp4();
			ex = result;
			if (partialResult == 0.0) {
				result = 1.0;
			}
			else
				for (t = (int) partialResult - 1; t > 0; t--)
					result = result * ex;
		}
		return result;
	}

	// Evaluate a unary + or -.  
	
	private double evalExp5() throws ParserException {
		double result;
		String op;

		op = "";
		if ((tokType == DELIMITER) && token.equals("+") || token.equals("-")) {
			op = token;
			getToken();
		}
		result = evalExp6();

		if (op.equals("-"))
			result = -result;

		return result;
	}

	// Process a parenthesized expression. 
	 
	private double evalExp6() throws ParserException {
		double result;

		if (token.equals("(")) {
			getToken();
			result = evalExp2();
			if (!token.equals(")"))
				handleErr(UNBALPARENS);
			getToken();
		}
		else
			result = atom();

		return result;
	}

	// Get the value of a number or variable.  
	
	private double atom() throws ParserException {
		double result = 0.0;

		switch (tokType) {
			case NUMBER:
				try {
					result = Double.parseDouble(token);
				}
				catch (NumberFormatException exc) {
					handleErr(SYNTAX);
				}
				getToken();
				break;
			case VARIABLE:
				result = findVar(token);
				getToken();
				break;
			default:
				handleErr(SYNTAX);
				break;
		}
		return result;
	}

	// Return the value of a variable.  
	private double findVar(String vname) throws ParserException {
		if (!Character.isLetter(vname.charAt(0))) {
			handleErr(SYNTAX);
			return 0.0;
		}
		return vars[Character.toUpperCase(vname.charAt(0)) - 'A'];
	}

	// Return a token to the input stream.  
	private void putBack() {
		if (token == EOE)
			return;
		for (int i = 0; i < token.length(); i++)
			expIdx--;
	}

	// Handle an error.  
	private void handleErr(int error) throws ParserException {
		String[] err = { "Syntax Error", "Unbalanced Parentheses",
			"No Expression Present", "Division by Zero" };

		throw new ParserException(err[error]);
	}

	// Obtain the next token.  
	private void getToken() {
		tokType = NONE;
		token = "";

		// Check for end of expression.  
		if (expIdx == exp.length()) {
			token = EOE;
			return;
		}

		// Skip over white space. 
		while (expIdx < exp.length()
				&& Character.isWhitespace(exp.charAt(expIdx)))
			++expIdx;

		// Trailing whitespace ends expression. 
		if (expIdx == exp.length()) {
			token = EOE;
			return;
		}

		if (isDelim(exp.charAt(expIdx))) { // is operator  
			token += exp.charAt(expIdx);
			expIdx++;
			tokType = DELIMITER;
		}
		else
			if (Character.isLetter(exp.charAt(expIdx))) { // is variable  
				while (!isDelim(exp.charAt(expIdx))) {
					token += exp.charAt(expIdx);
					expIdx++;
					if (expIdx >= exp.length())
						break;
				}
				tokType = VARIABLE;
			}
			else
				if (Character.isDigit(exp.charAt(expIdx))) { // is number  
					while (!isDelim(exp.charAt(expIdx))) {
						token += exp.charAt(expIdx);
						expIdx++;
						if (expIdx >= exp.length())
							break;
					}
					tokType = NUMBER;
				}
				else { // unknown character terminates expression 
					token = EOE;
					return;
				}
	}

	// Return true if c is a delimiter.  
	private boolean isDelim(char c) {
		if ((" +-/*%^=()".indexOf(c) != -1))
			return true;
		return false;
	}
	
	
	
			
}

This the code that given to me of MR. Sciwihze.. i need this code to if my gui want to call.

===============================================

public void actionPerformed(ActionEvent e){
		
		
			Parser calculate= new Parser();
		
		    String str = inputField.getText();
		    
		  	    
		    String answerString = "";
    try{
	         double resultField = calculate.evaluate(str);
	         
	         answerString += resultField;
	         
    } catch (ParserException pe){
    	
            answerString = pe.toString();
            
    }
    //DISPLAY ANSWER STRING IN WAY OF CHOOSING
}

===========================

Sorry i don't how to work this. I studying everyday the code, but i can't understand this...

Made some fixes because--

->The ActionListeners for the buttons weren't set.
->The ActionListener interface wasn't implemented
->A few "masks" needed to be removed

Here's the modified version--

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;



public class Calculator extends JFrame implements ActionListener{ // interface ActionListener wasn't set


private JLabel statusLabel;
private JTextField inputField, resultField;
private JButton calculate, clear, cancel;

	public Calculator(){

		super("Calculator in  MDAS and PEMDAS rules");
		Container container= getContentPane();
		container.setLayout(new FlowLayout());

		statusLabel = new JLabel();

		container.add(new JLabel("Expression: "));
		inputField = new JTextField (20);
		container.add(inputField);

		container.add(new JLabel("Result: "));
		resultField = new JTextField (10);
		container.add(resultField);

		//button for  Expression

		//calculate = new JButton();
		/*JButton*/ calculate = new JButton("Calculate");
		calculate.addActionListener(this); // action listener wasnt set
		container.add(calculate);

		//clear = new JButton();
		/*JButton*/ clear = new JButton("Clear");
		clear.addActionListener(this);
		container.add(clear);

		//cancel = new JButton();
		/*JButton*/ cancel = new JButton("Cancel");
		cancel.addActionListener(this);
		container.add(cancel);

		setSize( 500, 150 );
		setVisible( true );
	}

	public static void main (String args[]){
		Calculator application = new Calculator();
		application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	public void actionPerformed(ActionEvent e){

		if(e.getActionCommand().equalsIgnoreCase("Calculate")){
			Parser calc= new Parser();
			String str = inputField.getText();
			String answerString = "";
			try{
				double result = calc.evaluate(str); //
				answerString += result;
				resultField.setText(answerString);
			}catch (ParserException pe){
			//	answerString = pe.toString(); resultField.setText(answerString); // alternative method
				JOptionPane.showMessageDialog(null, pe); // show in message dialog
			}
		}
	//DISPLAY ANSWER STRING IN WAY OF CHOOSING
		else if(e.getActionCommand().equalsIgnoreCase("Clear")){ // for clearing
			resultField.setText("");
			inputField.setText("");
		}
		else if(e.getActionCommand().equalsIgnoreCase("Cancel")){ // for exiting
			System.exit(0);
		}
	}

/*
   This module contains the recursive descent
   parser that uses variables.
 */

// Exception class for parser errors.
	class ParserException extends Exception {
		String errStr;  // describes the error

		public ParserException(String str) {
			errStr = str;
		}

		public String toString() {
			return errStr;
		}
	}



	public class Parser {
		// These are the token types.
		final int NONE = 0;
		final int DELIMITER = 1;
		final int VARIABLE = 2;
		final int NUMBER = 3;

		// These are the types of syntax errors.
		final int SYNTAX = 0;
		final int UNBALPARENS = 1;
		final int NOEXP = 2;
		final int DIVBYZERO = 3;

		// This token indicates end-of-expression.
		final String EOE = "\0";

		private String exp; // refers to expression string
		private int expIdx; // current index into the expression
		private String token; // holds current token
		private int tokType; // holds token's type

		// Array for variables.
		private double vars[] = new double[26];

		// Parser entry point.
		public double evaluate(String expstr) throws ParserException {
			double result;
			exp = expstr;
			expIdx = 0;

			getToken();
			if (token.equals(EOE))
				handleErr(NOEXP); // no expression present

			// Parse and evaluate the expression.
			result = evalExp1();

			if (!token.equals(EOE)) // last token must be EOE
				handleErr(SYNTAX);

			return result;
		}

		// Process an assignment.
		private double evalExp1() throws ParserException {
			double result;
			int varIdx;
			int ttokType;
			String temptoken;

			if (tokType == VARIABLE) {
				// save old token
				temptoken = new String(token);
				ttokType = tokType;

				// Compute the index of the variable.
				varIdx = Character.toUpperCase(token.charAt(0)) - 'A';

				getToken();
				if (!token.equals("=")) {
					putBack(); // return current token
					// restore old token -- not an assignment
					token = new String(temptoken);
					tokType = ttokType;
				}
				else {
					getToken(); // get next part of exp
					result = evalExp2();
					vars[varIdx] = result;
					return result;
				}
			}

			return evalExp2();
		}

		// Add or subtract two terms.
		private double evalExp2() throws ParserException {
			char op;
			double result;
			double partialResult;

			result = evalExp3();

			while ((op = token.charAt(0)) == '+' || op == '-') {
				getToken();
				partialResult = evalExp3();
				switch (op) {
					case '-':
						result = result - partialResult;
						break;
					case '+':
						result = result + partialResult;
						break;
				}
			}
			return result;
		}

		// Multiply or divide two factors.

		private double evalExp3() throws ParserException {
			char op;
			double result;
			double partialResult;

			result = evalExp4();

			while ((op = token.charAt(0)) == '*' || op == '/' || op == '%') {
				getToken();
				partialResult = evalExp4();
				switch (op) {
					case '*':
						result = result * partialResult;
						break;
					case '/':
						if (partialResult == 0.0)
							handleErr(DIVBYZERO);
						result = result / partialResult;
						break;
					case '%':
						if (partialResult == 0.0)
							handleErr(DIVBYZERO);
						result = result % partialResult;
						break;
				}
			}
			return result;
		}

		// Process an exponent.
		private double evalExp4() throws ParserException {
			double result;
			double partialResult;
			double ex;
			int t;

			result = evalExp5();

			if (token.equals("^")) {
				getToken();
				partialResult = evalExp4();
				ex = result;
				if (partialResult == 0.0) {
					result = 1.0;
				}
				else
					for (t = (int) partialResult - 1; t > 0; t--)
						result = result * ex;
			}
			return result;
		}

		// Evaluate a unary + or -.

		private double evalExp5() throws ParserException {
			double result;
			String op;

			op = "";
			if ((tokType == DELIMITER) && token.equals("+") || token.equals("-")) {
				op = token;
				getToken();
			}
			result = evalExp6();

			if (op.equals("-"))
				result = -result;

			return result;
		}

		// Process a parenthesized expression.

		private double evalExp6() throws ParserException {
			double result;

			if (token.equals("(")) {
				getToken();
				result = evalExp2();
				if (!token.equals(")"))
					handleErr(UNBALPARENS);
				getToken();
			}
			else
				result = atom();

			return result;
		}

		// Get the value of a number or variable.

		private double atom() throws ParserException {
			double result = 0.0;

			switch (tokType) {
				case NUMBER:
					try {
						result = Double.parseDouble(token);
					}
					catch (NumberFormatException exc) {
						handleErr(SYNTAX);
					}
					getToken();
					break;
				case VARIABLE:
					result = findVar(token);
					getToken();
					break;
				default:
					handleErr(SYNTAX);
					break;
			}
			return result;
		}

		// Return the value of a variable.
		private double findVar(String vname) throws ParserException {
			if (!Character.isLetter(vname.charAt(0))) {
				handleErr(SYNTAX);
				return 0.0;
			}
			return vars[Character.toUpperCase(vname.charAt(0)) - 'A'];
		}

		// Return a token to the input stream.
		private void putBack() {
			if (token == EOE)
				return;
			for (int i = 0; i < token.length(); i++)
				expIdx--;
		}

		// Handle an error.
		private void handleErr(int error) throws ParserException {
			String[] err = { "Syntax Error", "Unbalanced Parentheses",
				"No Expression Present", "Division by Zero" };

			throw new ParserException(err[error]);
		}

		// Obtain the next token.
		private void getToken() {
			tokType = NONE;
			token = "";

			// Check for end of expression.
			if (expIdx == exp.length()) {
				token = EOE;
				return;
			}

			// Skip over white space.
			while (expIdx < exp.length()
					&& Character.isWhitespace(exp.charAt(expIdx)))
				++expIdx;

			// Trailing whitespace ends expression.
			if (expIdx == exp.length()) {
				token = EOE;
				return;
			}

			if (isDelim(exp.charAt(expIdx))) { // is operator
				token += exp.charAt(expIdx);
				expIdx++;
				tokType = DELIMITER;
			}
			else
				if (Character.isLetter(exp.charAt(expIdx))) { // is variable
					while (!isDelim(exp.charAt(expIdx))) {
						token += exp.charAt(expIdx);
						expIdx++;
						if (expIdx >= exp.length())
							break;
					}
					tokType = VARIABLE;
				}
				else
					if (Character.isDigit(exp.charAt(expIdx))) { // is number
						while (!isDelim(exp.charAt(expIdx))) {
							token += exp.charAt(expIdx);
							expIdx++;
							if (expIdx >= exp.length())
								break;
						}
						tokType = NUMBER;
					}
					else { // unknown character terminates expression
						token = EOE;
						return;
					}
		}

		// Return true if c is a delimiter.
		private boolean isDelim(char c) {
			if ((" +-/*%^=()".indexOf(c) != -1))
				return true;
			return false;
		}

	}

}

By the way sciwizeh your algorithms never cease to amaze me.

ha, as i have said before i didn't come up with this, it was in a book, and it amazes me too, i would never have used recursion in this way

in about a day or two, i will probably upload my gui program for this to my site along with a minesweeper game and a paint program all in java

I'm sorry to sciwizeh, but i thankful of you it because you give me a sample code of that..

why apologize? i joined daniweb to ask the same question, just more complicated, and i found a book with code, and decided i could answer questions too, here is a simple calculator that i used that code with, you can extractthe source from the jar if you like, it is there, but don't claim you wrote it pls

Hi Guys,

I got it. In five years of not login in this thread and discussion of "MDAS and PEMDAS Calculator its solve" In my college years, I go to DaniWeb Forum to ask some questions how to solve the MDAS and PEMDAS Calculator, on that day I'm so freak and not Understand the conversation, because of the deadline of our project. On that month I give up to solve a problem, I decided to create a new one "With the help of reference: the art of Java: Suggested by Master sciwish, I used and understand the book. On that day I create a new MDAS and PEMDAS Calculator, but it's not GUI oh JFRAME.” Today, that I am a Professor of one Institution that opens the BSCS/BSIT course. I'm handling the Programming 2 Areas. Starting of our class, I told to the student that we used a higher programming, the "The Java Programming with the Database Application, I discussed already the theory of database application, but suddenly because of not good facilities in our laboratories on that class, I told my student to reshift oh focus java programming, because some of my students can't understand the higher level of Java using a Web." I discussed to my student a basic Java first, until they understand. I gave them a source how to create a java programming; I gave them a simple project to understand the Java Programming. In our Pre- Final Exam they had a Calculator Project MDAS and PEMDAS. In my class there are 2 students that are interested to compile their project, so i gave them the idea how creating their project? I told them to go to the DaneWeb because all of them question are already catered on this forum, I told them to visit the "Need help for MDAS rules in a Calculator" and Understand the conversation, I introduced them that I am a user of "darlineth", sciwizeh is one forum member that I recognized to them. 2 of my students compile this and understand the instruction. With the 30 minutes, they solve and compile the codes. But on that day, I also create my own again (because my backup was deleted on my PC). They present the program, that's it the going calculate what they inputted.

2 of my students I recognized because of their interest to learn and want to increase their knowledge. In five years the problem is solved.
Case Closed.

/*
 Sources and Reference
 * The Art Java
 * Java Consultant Master Sciwizeh
 * 
*Compiled by: Darryl M. Nuyda, MM-ITM, Sharmille Angel and Anne Dela Cruz
 */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class NewCalculator extends JFrame implements ActionListener{ // interface ActionListener wasn't set
private JLabel statusLabel;
private JTextField inputField, resultField;
private JButton calculate, clear, cancel;
    public NewCalculator(){
        super("Calculator in  MDAS and PEMDAS rules");
        Container container= getContentPane();
        container.setLayout(new FlowLayout());
        statusLabel = new JLabel();
        container.add(new JLabel("Expression: "));
        inputField = new JTextField (20);
        container.add(inputField);
        container.add(new JLabel("Result: "));
        resultField = new JTextField (10);
        container.add(resultField);
        //button for  Expression
        //calculate = new JButton();

                /*JButton*/ 
                calculate = new JButton("Calculate");
        calculate.addActionListener(this); // action listener wasnt set
        container.add(calculate);
        //clear = new JButton();

                /*JButton*/ 
                clear = new JButton("Clear");
        clear.addActionListener(this);
        container.add(clear);
        //cancel = new JButton();

                /*JButton*/ 
                cancel = new JButton("Cancel");
        cancel.addActionListener(this);
        container.add(cancel);
        setSize( 500, 150 );
        setVisible( true );
    }
    public static void main (String args[]){
        NewCalculator application = new NewCalculator();
        application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public void actionPerformed(ActionEvent e){
        if(e.getActionCommand().equalsIgnoreCase("Calculate")){
            Parser calc= new Parser();
            String str = inputField.getText();
            String answerString = "";
            try{
                double result = calc.evaluate(str); //
                answerString += result;
                resultField.setText(answerString);
            }catch (ParserException pe){
            //  answerString = pe.toString(); resultField.setText(answerString); // alternative method
                JOptionPane.showMessageDialog(null, pe); // show in message dialog
            }
        }


    //DISPLAY ANSWER STRING IN WAY OF CHOOSING
        else if(e.getActionCommand().equalsIgnoreCase("Clear")){ // for clearing
            resultField.setText("");
            inputField.setText("");
        }
        else if(e.getActionCommand().equalsIgnoreCase("Cancel")){ // for exiting
            System.exit(0);
        }
    }
/*
   This module contains the recursive descent
   parser that uses variables.
 */
// Exception class for parser errors.
    class ParserException extends Exception {
        String errStr;  // describes the error
        public ParserException(String str) {
            errStr = str;
        }
        public String toString() {
            return errStr;
        }
    }
    public class Parser {
        // These are the token types.
        final int NONE = 0;
        final int DELIMITER = 1;
        final int VARIABLE = 2;
        final int NUMBER = 3;
        // These are the types of syntax errors.
        final int SYNTAX = 0;
        final int UNBALPARENS = 1;
        final int NOEXP = 2;
        final int DIVBYZERO = 3;
        // This token indicates end-of-expression.
        final String EOE = "\0";
        private String exp; // refers to expression string
        private int expIdx; // current index into the expression
        private String token; // holds current token
        private int tokType; // holds token's type
        // Array for variables.
        private double vars[] = new double[26];
        // Parser entry point.
        public double evaluate(String expstr) throws ParserException {
            double result;
            exp = expstr;
            expIdx = 0;
            getToken();
            if (token.equals(EOE))
                handleErr(NOEXP); // no expression present
            // Parse and evaluate the expression.
            result = evalExp1();
            if (!token.equals(EOE)) // last token must be EOE
                handleErr(SYNTAX);
            return result;
        }
        // Process an assignment.
        private double evalExp1() throws ParserException {
            double result;
            int varIdx;
            int ttokType;
            String temptoken;
            if (tokType == VARIABLE) {
                // save old token
                temptoken = new String(token);
                ttokType = tokType;
                // Compute the index of the variable.
                varIdx = Character.toUpperCase(token.charAt(0)) - 'A';
                getToken();
                if (!token.equals("=")) {
                    putBack(); // return current token
                    // restore old token -- not an assignment
                    token = new String(temptoken);
                    tokType = ttokType;
                }
                else {
                    getToken(); // get next part of exp
                    result = evalExp2();
                    vars[varIdx] = result;
                    return result;
                }
            }
            return evalExp2();
        }
        // Add or subtract two terms.
        private double evalExp2() throws ParserException {
            char op;
            double result;
            double partialResult;
            result = evalExp3();
            while ((op = token.charAt(0)) == '+' || op == '-') {
                getToken();
                partialResult = evalExp3();
                switch (op) {
                    case '-':
                        result = result - partialResult;
                        break;
                    case '+':
                        result = result + partialResult;
                        break;
                }
            }
            return result;
        }
        // Multiply or divide two factors.
        private double evalExp3() throws ParserException {
            char op;
            double result;
            double partialResult;
            result = evalExp4();
            while ((op = token.charAt(0)) == '*' || op == '/' || op == '%') {
                getToken();
                partialResult = evalExp4();
                switch (op) {
                    case '*':
                        result = result * partialResult;
                        break;
                    case '/':
                        if (partialResult == 0.0)
                            handleErr(DIVBYZERO);
                        result = result / partialResult;
                        break;
                    case '%':
                        if (partialResult == 0.0)
                            handleErr(DIVBYZERO);
                        result = result % partialResult;
                        break;
                }
            }
            return result;
        }
        // Process an exponent.
        private double evalExp4() throws ParserException {
            double result;
            double partialResult;
            double ex;
            int t;
            result = evalExp5();
            if (token.equals("^")) {
                getToken();
                partialResult = evalExp4();
                ex = result;
                if (partialResult == 0.0) {
                    result = 1.0;
                }
                else
                    for (t = (int) partialResult - 1; t > 0; t--)
                        result = result * ex;
            }
            return result;
        }
        // Evaluate a unary + or -.
        private double evalExp5() throws ParserException {
            double result;
            String op;
            op = "";
            if ((tokType == DELIMITER) && token.equals("+") || token.equals("-")) {
                op = token;
                getToken();
            }
            result = evalExp6();
            if (op.equals("-"))
                result = -result;
            return result;
        }
        // Process a parenthesized expression.
        private double evalExp6() throws ParserException {
            double result;
            if (token.equals("(")) {
                getToken();
                result = evalExp2();
                if (!token.equals(")"))
                    handleErr(UNBALPARENS);
                getToken();
            }
            else
                result = atom();
            return result;
        }
        // Get the value of a number or variable.
        private double atom() throws ParserException {
            double result = 0.0;
            switch (tokType) {
                case NUMBER:
                    try {
                        result = Double.parseDouble(token);
                    }
                    catch (NumberFormatException exc) {
                        handleErr(SYNTAX);
                    }
                    getToken();
                    break;
                case VARIABLE:
                    result = findVar(token);
                    getToken();
                    break;
                default:
                    handleErr(SYNTAX);
                    break;
            }
            return result;
        }
        // Return the value of a variable.
        private double findVar(String vname) throws ParserException {
            if (!Character.isLetter(vname.charAt(0))) {
                handleErr(SYNTAX);
                return 0.0;
            }
            return vars[Character.toUpperCase(vname.charAt(0)) - 'A'];
        }
        // Return a token to the input stream.
        private void putBack() {
            if (token == EOE)
                return;
            for (int i = 0; i < token.length(); i++)
                expIdx--;
        }
        // Handle an error.
        private void handleErr(int error) throws ParserException {
            String[] err = { "Syntax Error", "Unbalanced Parentheses",
                "No Expression Present", "Division by Zero" };
            throw new ParserException(err[error]);
        }
        // Obtain the next token.
        private void getToken() {
            tokType = NONE;
            token = "";
            // Check for end of expression.
            if (expIdx == exp.length()) {
                token = EOE;
                return;
            }
            // Skip over white space.
            while (expIdx < exp.length()
                    && Character.isWhitespace(exp.charAt(expIdx)))
                ++expIdx;
            // Trailing whitespace ends expression.
            if (expIdx == exp.length()) {
                token = EOE;
                return;
            }
            if (isDelim(exp.charAt(expIdx))) { // is operator
                token += exp.charAt(expIdx);
                expIdx++;
                tokType = DELIMITER;
            }
            else
                if (Character.isLetter(exp.charAt(expIdx))) { // is variable
                    while (!isDelim(exp.charAt(expIdx))) {
                        token += exp.charAt(expIdx);
                        expIdx++;
                        if (expIdx >= exp.length())
                            break;
                    }
                    tokType = VARIABLE;
                }
                else
                    if (Character.isDigit(exp.charAt(expIdx))) { // is number
                        while (!isDelim(exp.charAt(expIdx))) {
                            token += exp.charAt(expIdx);
                            expIdx++;
                            if (expIdx >= exp.length())
                                break;
                        }
                        tokType = NUMBER;
                    }
                    else { // unknown character terminates expression
                        token = EOE;
                        return;
                    }
        }
        // Return true if c is a delimiter.
        private boolean isDelim(char c) {
            if ((" +-/*%^=()".indexOf(c) != -1))
                return true;
            return false;
        }
    }
}

here is the other code without Button

Sourcces : The Art of Java

Calc.java

/*
Compiled by: Darryl M. Nuyda

*/
// A simple calculator applet. 

//coded by improfdar@gmail.com - the art of Java

import java.awt.*; 
import java.awt.event.*; 
import java.applet.*; 
/* 
  <applet code="Calc" width=200 height=150> 
  </applet> 
*/ 

public class Calc extends Applet 
  implements ActionListener { 

  TextField expText, resText; 
  Parser p;  

  public void init() { 
    Label heading = new 
          Label("Expression Calculator ", Label.CENTER); 

    Label explab = new Label("Expression ", Label.CENTER); 
    Label reslab = new Label("Result     ", Label.CENTER); 
    expText = new TextField(24); 
    resText = new TextField(24); 

    resText.setEditable(false); // result field for display only 

    add(heading); 
    add(explab); 
    add(expText); 
    add(reslab); 
    add(resText); 

    /* Register expression text field 
       to receive action events. */ 
    expText.addActionListener(this); 

    // create parser 
    p = new Parser();  
  } 

  // User pressed Enter. 
  public void actionPerformed(ActionEvent ae) { 
    repaint(); 
  } 

  public void paint(Graphics g) { 
    double result = 0.0; 
    String expstr = expText.getText(); 

    try { 
      if(expstr.length() != 0)  
        result = p.evaluate(expstr);  

// To clear expression after ENTER is pressed 
// use the folloing line: 
//    expText.setText(""); 

      resText.setText(Double.toString(result)); 

      showStatus(""); // erase any previous error message 
    } catch (ParserException exc) { 
      showStatus(exc.toString()); 
      resText.setText(""); 
    } 
  } 
}

parser.java

/*   
   Compiled by: Darry M. Nuyda 

Code by: improfdar@gmail.com

*/  

// Exception class for parser errors.  
class ParserException extends Exception {  
  String errStr; // describes the error 

  public ParserException(String str) { 
    errStr = str; 
  }   

  public String toString() {  
    return errStr; 
  }  
}  

class Parser {  
  // These are the token types. 
  final int NONE = 0; 
  final int DELIMITER = 1; 
  final int VARIABLE = 2; 
  final int NUMBER = 3; 

  // These are the types of syntax errors. 
  final int SYNTAX = 0; 
  final int UNBALPARENS = 1; 
  final int NOEXP = 2; 
  final int DIVBYZERO = 3; 

   // This token indicates end-of-expression. 
  final String EOE = "\0"; 

  private String exp;   // refers to expression string  
  private int expIdx;   // current index into the expression  
  private String token; // holds current token  
  private int tokType;  // holds token's type  

  // Array for variables.  
  private double vars[] = new double[26];  

  // Parser entry point.  
  public double evaluate(String expstr) throws ParserException 
  {  
    double result;  
    exp = expstr;  
    expIdx = 0;   

    getToken();  
    if(token.equals(EOE)) 
      handleErr(NOEXP); // no expression present  

    // Parse and evaluate the expression. 
    result = evalExp1();  

    if(!token.equals(EOE)) // last token must be EOE  
      handleErr(SYNTAX);  

    return result;  
  }  

  // Process an assignment.  
  private double evalExp1() throws ParserException 
  {  
    double result; 
    int varIdx;  
    int ttokType;  
    String temptoken;  

    if(tokType == VARIABLE) {  
      // save old token  
      temptoken = new String(token);  
      ttokType = tokType;  

      // Compute the index of the variable.  
      varIdx = Character.toUpperCase(token.charAt(0)) - 'A';  

      getToken();  
      if(!token.equals("=")) {  
        putBack(); // return current token  
        // restore old token -- not an assignment  
        token = new String(temptoken);  
        tokType = ttokType;  
      }  
      else {  
        getToken(); // get next part of exp  
        result = evalExp2();  
        vars[varIdx] = result;  
        return result;  
      }  
    }  

    return evalExp2();  
  }  

  // Add or subtract two terms.  
  private double evalExp2() throws ParserException 
  {  
    char op;  
    double result; 
    double partialResult;  

    result = evalExp3();  

    while((op = token.charAt(0)) == '+' || op == '-') {  
      getToken();  
      partialResult = evalExp3();  
      switch(op) {  
        case '-':  
          result = result - partialResult;  
          break;  
        case '+':  
          result = result + partialResult;  
          break;  
      }  
    }  
    return result; 
  }  

  // Multiply or divide two factors.  
  private double evalExp3() throws ParserException 
  {  
    char op;  
    double result; 
    double partialResult;  

    result = evalExp4();  

    while((op = token.charAt(0)) == '*' ||  
           op == '/' || op == '%') {  
      getToken();  
      partialResult = evalExp4();  
      switch(op) {  
        case '*':  
          result = result * partialResult;  
          break;  
        case '/':  
          if(partialResult == 0.0)  
            handleErr(DIVBYZERO);  
          result = result / partialResult;  
          break;  
        case '%':  
          if(partialResult == 0.0)  
            handleErr(DIVBYZERO);  
          result = result % partialResult;  
          break;  
      }  
    }  
    return result; 
  }  

 // Process an exponent.  
 private double evalExp4() throws ParserException 
  {  
    double result; 
    double partialResult; 
    double ex;  
    int t;  

    result = evalExp5();  

    if(token.equals("^")) {  
      getToken();  
      partialResult = evalExp4();  
      ex = result;  
      if(partialResult == 0.0) {  
        result = 1.0;  
      } else  
        for(t=(int)partialResult-1; t > 0; t--)  
          result = result * ex;  
    }  
    return result; 
  }  

  // Evaluate a unary + or -.  
  private double evalExp5() throws ParserException 
  {  
    double result; 
    String  op;  

    op = "";  
    if((tokType == DELIMITER) &&  
        token.equals("+") || token.equals("-")) {  
      op = token;  
      getToken();  
    }  
    result = evalExp6();  

    if(op.equals("-")) result = -result; 

    return result;  
  }  

  // Process a parenthesized expression.  
  private double evalExp6() throws ParserException 
  {  
    double result; 

    if(token.equals("(")) {  
      getToken();  
      result = evalExp2();  
      if(!token.equals(")"))  
        handleErr(UNBALPARENS);  
      getToken();  
    }  
    else result = atom();  

    return result; 
  }  

  // Get the value of a number or variable.  
  private double atom() throws ParserException  
  {  
    double result = 0.0; 

    switch(tokType) {  
      case NUMBER:  
        try {  
          result = Double.parseDouble(token);  
        } catch (NumberFormatException exc) {  
          handleErr(SYNTAX);  
        }  
        getToken();  
        break; 
      case VARIABLE:  
        result = findVar(token);  
        getToken();  
        break;  
      default:  
        handleErr(SYNTAX);  
        break;  
    }  
    return result; 
  }  

   // Return the value of a variable.  
  private double findVar(String vname) throws ParserException 
  {  
    if(!Character.isLetter(vname.charAt(0))){  
      handleErr(SYNTAX);  
      return 0.0;  
    }  
    return vars[Character.toUpperCase(vname.charAt(0))-'A'];  
  }  

  // Return a token to the input stream.  
  private void putBack()    
  {  
    if(token == EOE) return; 
    for(int i=0; i < token.length(); i++) expIdx--;  
  }  

  // Handle an error.  
  private void handleErr(int error) throws ParserException 
  {  
    String[] err = {  
      "Syntax Error",  
      "Unbalanced Parentheses",  
      "No Expression Present",  
      "Division by Zero"  
    };  

    throw new ParserException(err[error]);  
  }  

  // Obtain the next token.  
  private void getToken()  
  {  
    tokType = NONE;  
    token = "";  

    // Check for end of expression.  
    if(expIdx == exp.length()) { 
      token = EOE; 
      return; 
    } 

    // Skip over white space. 
    while(expIdx < exp.length() &&  
      Character.isWhitespace(exp.charAt(expIdx))) ++expIdx;  

    // Trailing whitespace ends expression. 
    if(expIdx == exp.length()) { 
      token = EOE; 
      return; 
    } 

    if(isDelim(exp.charAt(expIdx))) { // is operator  
      token += exp.charAt(expIdx);  
      expIdx++;  
      tokType = DELIMITER;  
    }  
    else if(Character.isLetter(exp.charAt(expIdx))) { // is variable  
      while(!isDelim(exp.charAt(expIdx))) {  
        token += exp.charAt(expIdx);  
        expIdx++;  
        if(expIdx >= exp.length()) break;  
      }  
      tokType = VARIABLE;  
    }  
    else if(Character.isDigit(exp.charAt(expIdx))) { // is number  
      while(!isDelim(exp.charAt(expIdx))) {  
        token += exp.charAt(expIdx);  
        expIdx++;  
        if(expIdx >= exp.length()) break;  
      }  
      tokType = NUMBER;  
    }  
    else { // unknown character terminates expression 
      token = EOE; 
      return; 
    } 
  }  

  // Return true if c is a delimiter.  
  private boolean isDelim(char c)  
  {  
    if((" +-/*%^=()".indexOf(c) != -1))  
      return true;  
    return false;  
  }  
}

My Post 1 and Post is Compiled and 100% MDAS and PEMDAS calculator.

you are free to copy and present this to your professor.

P.S: this code is help by "the art of Java"

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.