Arithmetic expression calculator
Hello everybody!
...hi dr nick
Anyways I have this code that compiles but won't complete the actual function it serves I need to calculate expressions such as 2+3+9-4 then hit the calculate button then it is suppose to be displayed in the other field however I don't know where it it going wrong
Code:
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
import java.awt.*;
import java.io.*;
import java.util.*;
public class CalcExp extends JPanel
{
private JTextField jTextField1 = new JTextField(10);
private JTextField jTextField2 = new JTextField(10);
private JButton jButton1 = new JButton("Calculate");
public CalcExp()
{
/*jTextField1.setEditable(true);
jTextField2.setEditable(false);
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton1ActionPerformed(e);
}
});
add(jTextField1);
add(jTextField2);
add(jButton1);*/
// draw the interface
Panel northP = new Panel(); // input
Panel centerP = new Panel(); // controls
Panel southP = new Panel(); // output
// input panel
northP.setLayout( new BorderLayout() );
northP.add( "Center", jTextField1 = new JTextField(30) );
// controls panel
centerP.add( jButton1 = new JButton("Calculate") );
// output panel
southP.setLayout( new BorderLayout() );
southP.add( "Center", jTextField2 = new JTextField(30) );
jTextField2.setEditable( false );
// add all the panels
setLayout( new BorderLayout() );
add( "North", northP );
add( "Center", centerP );
add( "South", southP );
return;
}
public boolean action( Event ev, Object arg )
{
if (ev.target instanceof JButton)
{
if ("Calculate".equals(arg))
process();
return true;
}
return false;
}
// process the input string
protected void process()
{
// get the input string
String inputString = jTextField1.getText();
// trim the string
inputString = inputString.trim();
// ensure there are characters to process
if (inputString.length() > 0)
// check syntax, evaluate and display results if correct
if ( checkSyntax() )
jTextField2.setText( " = " + evaluate() );
}
// checkSyntax checks the syntax of the input string, calls reportError
// to report any errors. Returns true if the string is part of the
// grammar, false if an error was found.
protected boolean checkSyntax()
{
int opCount = 1; // start with a value
boolean hasDec = false; // does the current # have a decimal component?
int i;
String inputString = jTextField1.getText();
// check each character
for (i = 0; i < inputString.length(); i++)
switch(inputString.charAt(i))
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
opCount = 0;
break;
case '.':
if (((opCount += 2) > 2) || hasDec)
return reportError(i);
hasDec = true;
break;
case '/':
case '*':
if (opCount++ > 0)
return reportError(i);
hasDec = false;
break;
case '+':
case '-':
if (opCount++ > 1)
return reportError(i);
hasDec = false;
break;
default:
return reportError(i);
}
// make sure expression ends with a value
if (opCount > 0)
return reportError(i);
else
return true;
}
// evaluate - returns the value obtained by evaluating the input expression
protected double evaluate()
{
String inputString = jTextField1.getText();
// temp token handle
String tok1, tok2;
// create a string tokenizer object, keeping the delimiters as tokens
StringTokenizer tokens = new StringTokenizer( inputString, "+-/*", true );
// get the first token and put its value into result
if ((tok1 = tokens.nextToken()).equals("+"))
tok1 = tokens.nextToken();
else if (tok1.equals("-"))
tok1 = "-".concat(tokens.nextToken());
double result = new Double(tok1).doubleValue();
// evaluate the expression
while (tokens.hasMoreTokens())
{
// get the operator token
tok1 = tokens.nextToken();
// get the second operand token
if ((tok2 = tokens.nextToken()).equals("+"))
tok2 = tokens.nextToken();
else if (tok2.equals("-"))
tok2 = "-".concat(tokens.nextToken());
// evaluate the subexpression
switch (tok1.charAt(0))
{
case '+':
result += new Double(tok2).doubleValue();
break;
case '-':
result -= new Double(tok2).doubleValue();
break;
case '/':
result /= new Double(tok2).doubleValue();
break;
case '*':
result *= new Double(tok2).doubleValue();
break;
}
}
return result;
}
// reportError - Reports a syntax error to outputTA. Always
// returns false.
protected boolean reportError( int index )
{
String inputString = jTextField1.getText();
// create a new string with the first line of output
String outputString = new String("Syntax error:\n");
// echo the user input as second line
outputString = outputString.concat( inputString );
outputString = outputString.concat( "\n" );
// display pointer to error position as third line
for (int i = 0; i < index; i++)
outputString = outputString.concat(" ");
outputString = outputString.concat("^");
// copy the output string text to the output text area
jTextField2.setText( outputString );
return false;
}
private static void createAndShowUI() {
JFrame frame = new JFrame("M009");
frame.getContentPane().add(new CalcExp());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}}