Question

Please help to resolve my error. This Java code is supposed to evaluate one line equation...

Please help to resolve my error. This Java code is supposed to evaluate one line equation of the form X Operator =Z where X is any name of a variable and Y and Z are integers By user in equation solver window. Currently the code executes expressions such as Y Operator(+,-,*,/) Z

package Equations;

/**
* This program evaluates arithmetic expressions
*/

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, term3, equals;
equals = "=";

s = s.trim(); //this takes all the white space out on the end

//s.insert(" ",s.indexOf('=')+1);
//s.insert(" ",s.indexOf('=')-1);

//modify s so that there are spaces around the operator and/or equals sign (extra spaces are ok but must have 1 space)
//only works for 3 or 5 tokens in this program(the else part of the if-statement)

StringTokenizer terms = new StringTokenizer(s);

if (terms.countTokens() == 3)
{
term1 = terms.nextToken();
op = terms.nextToken();
term2 = terms.nextToken();
return evaluate(term1, op, term2);
}
else if(terms.countTokens() == 5)
{
term1 = terms.nextToken();
op = terms.nextToken();
term2 = terms.nextToken();
equals = terms.nextToken();
term3 = terms.nextToken();
return evaluate(term1, op, term2, term3);
}
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)
//write another method evaluate with 4 parameters for the second part of the problem
{
String result;

if (op.length() != 1)
return ARROW + "Syntax error";

char opSign = op.charAt(0); //why is this at 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)
result = "==> Divide by zero error!";
else // a%b==0
result = "= " + (a / b);
break;
case '/':
if(b==0)
result = "==> Divide by zero error!";
else if(a%b>0)
result = "==> " + a + " is not evenly divisible by " + b;
else //a%b==0
result = "= " + (a / b);
break;

default:
result = ARROW + "Invalid operation";
break;
}
return result;
}

private String evaluate(String term1, String op, String term2, String term3)
{
String result;

if (op.length() != 1)
return ARROW + "Syntax error";

char opSign = op.charAt(0);
int b = Integer.parseInt(term2);
int c = Integer.parseInt(term3);
int a = Integer.parseInt(term1);


switch (opSign)
{
case '+':
result = ARROW + a + "= " + (c - b);
break;

case '-':
result = a + "= " + (c + b);
break;

case '*':
if(b==0)
result = ARROW + "No Solution";
else if(c%b != 0)
result = ARROW + "The answer is not an integer";
else
result = ARROW + a + "= " + (c / b);
break;

case '%': //still needs work
if(b==0)
result = ARROW + "Divide by zero error!";
else // a%b==0
result = JOptionPane.showInputDialog(term1 + " = " + b + "n " + " + " + c + "where n>=0;");
break;

case '/':
if(b==0)
result = ARROW + "Divide by zero error!";
else //a%b==0
result = ARROW + a + "= " + (c * b);
break;

default:
result = ARROW + "Invalid operation";
break;
}
return result;
}

public static void main(String args[])
{

EquationSolver panel = new EquationSolver();

}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Modified Program:

/**
* This program evaluates arithmetic expressions
*/

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, term3, equals;
equals = "=";

s = s.trim(); //this takes all the white space out on the end

//s.insert(" ",s.indexOf('=')+1);
//s.insert(" ",s.indexOf('=')-1);

//modify s so that there are spaces around the operator and/or equals sign (extra spaces are ok but must have 1 space)
//only works for 3 or 5 tokens in this program(the else part of the if-statement)

StringTokenizer terms = new StringTokenizer(s, "=+/*-%");
if (terms.countTokens() == 2) {

term1 = terms.nextToken();
if (s.contains("+"))
op = "+";
else if (s.contains("-"))
op = "-";
else if (s.contains("/"))
op = "/";
else if (s.contains("*"))
op = "*";
else if (s.contains("%"))
op = "%";
else return ARROW + "Syntax error";
term2 = terms.nextToken();
return evaluate(term1, op, term2);
} else if (terms.countTokens() == 3) {
term1 = terms.nextToken();
if (s.contains("+"))
op = "+";
else if (s.contains("-"))
op = "-";
else if (s.contains("/"))
op = "/";
else if (s.contains("*"))
op = "*";
else if (s.contains("%"))
op = "%";
else return ARROW + "Syntax error";

term2 = terms.nextToken();
term3 = terms.nextToken();
return evaluate(term1, op, term2, term3);
} 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)
//write another method evaluate with 4 parameters for the second part of the problem
{
String result;

if (op.length() != 1)
return ARROW + "Syntax error";

char opSign = op.charAt(0); //why is this at 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)
result = "==> Divide by zero error!";
else // a%b==0
result = "= " + (a / b);
break;
case '/':
if (b == 0)
result = "==> Divide by zero error!";
else if (a % b > 0)
result = "==> " + a + " is not evenly divisible by " + b;
else //a%b==0
result = "= " + (a / b);
break;

default:
result = ARROW + "Invalid operation";
break;
}
return result;
}
private String evaluate(String term1, String op, String term2, String term3) {
String result;


char opSign = op.charAt(0);
int b = Integer.parseInt(term2);
int c = Integer.parseInt(term3);


switch (opSign) {
case '+':
result = ARROW + term1 + "= " + (c - b);
break;

case '-':
result = ARROW + term1 + "= " + (c + b);
break;

case '*':
if (b == 0)
result = ARROW + "No Solution";
else if (c % b != 0)
result = ARROW + "The answer is not an integer";
else
result = ARROW + term1 + "= " + (c / b);
break;

case '%': //still needs work
if (b == 0)
result = ARROW + "Divide by zero error!";
else // a%b==0
result = JOptionPane.showInputDialog(term1 + " = " + b + "n " + " + " + c + "where n>=0;");
break;

case '/':
if (b == 0)
result = ARROW + "Divide by zero error!";
else //a%b==0
result = ARROW + term1 + "= " + (c * b);
break;

default:
result = ARROW + "Invalid operation";
break;
}
return result;
}

public static void main(String args[]) {

EquationSolver panel = new EquationSolver();

}
}

Output:

Add a comment
Know the answer?
Add Answer to:
Please help to resolve my error. This Java code is supposed to evaluate one line equation...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • The names of the two input files as well as the output file are supposed to be provided as arguments. Could you please fix it? Thanks. DPriorityQueue.java: // Import the required classes import java....

    The names of the two input files as well as the output file are supposed to be provided as arguments. Could you please fix it? Thanks. DPriorityQueue.java: // Import the required classes import java.io.*; import java.util.*; //Create the class public class DPriorityQueue { //Declare the private members variables. private int type1,type2; private String CostInTime[][], SVertex, DVertex; private List<String> listOfTheNodes; private Set<String> List; private List<Root> ListOfVisitedNode; private HashMap<String, Integer> minimalDistance; private HashMap<String, Integer> distOfVertices; private PriorityQueue<City> priorityQueue; // prove the definition...

  • (Reading & Writing Business Objects) I need to have my Classes be able to talk to...

    (Reading & Writing Business Objects) I need to have my Classes be able to talk to Files. How do I make it such that I can look in a File for an account number and I am able to pull up all the details? The file should be delimited by colons (":"). The Code for testing 'Select' that goes in main is: Account a1 = new Account(); a1.select(“90001”); a1.display(); Below is what it should look like for accounts 90000:3003:SAV:8855.90 &...

  • Help! Not sure how to create this java program to run efficiently. Current code and assignment...

    Help! Not sure how to create this java program to run efficiently. Current code and assignment attached. Assignment :Write a class Movies.java that reads in a movie list file (movies.txt). The file must contain the following fields: name, genre, and time. Provide the user with the options to sort on each field. Allow the user to continue to sort the list until they enter the exit option. ---------------------------------------------------------- import java.util.*; import java.io.*; public class Movies { String movieTitle; String movieGenre;...

  • I am getting this Error can you please fix my Java code. import java.awt.Dialog; import java.awt.Label;...

    I am getting this Error can you please fix my Java code. import java.awt.Dialog; import java.awt.Label; import java.awt.TextArea; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class Fall_2017 {    public TextArea courseInput;    public Label textAreaLabel;    public JButton addData;    public Dialog confirmDialog;    HashMap<Integer, ArrayList<String>> students;    public Fall_2017(){    courseInput = new TextArea(20, 40);    textAreaLabel = new Label("Student's data:");    addData = new JButton("Add...

  • JAVA: How do I output all the data included for each employee? I can only get...

    JAVA: How do I output all the data included for each employee? I can only get it to output the name, monthly salary and annual salary, but only from the Employee.java file, not Salesman.java or Executive.java. Employee.java package project1; public class Employee { private String name; private int monthlySalary; public Employee(String name, int monthlySalary) { this.name = name; this.monthlySalary = monthlySalary; } public int getAnnualSalary() { int totalPay = 0; totalPay = 12 * monthlySalary; return totalPay; } public String...

  • Java BlackJack Game: Help with 1-4 using the provided code below Source code for Project3.java: import...

    Java BlackJack Game: Help with 1-4 using the provided code below Source code for Project3.java: import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; public class Project3 extends JFrame implements ActionListener { private static int winxpos = 0, winypos = 0; // place window here private JButton exitButton, hitButton, stayButton, dealButton, newGameButton; private CardList theDeck = null; private JPanel northPanel; private MyPanel centerPanel; private static JFrame myFrame = null; private CardList playerHand = new CardList(0); private CardList dealerHand = new CardList(0);...

  • Convert infix to postfix, and evaluate postfix using custom Stack created using a singly linked list....

    Convert infix to postfix, and evaluate postfix using custom Stack created using a singly linked list. This is only supposed to use THAT method, calling a normal Stack will give me a zero. I do have the conversion to postfix, but there may be error in there. But the main problem currently is the evaluation of postfix. I keep getting an error that I made for an empty stack, which I will include. For testing it is only supposed to...

  • Java Programming: Hi, I need help Modifying my code that will throw an IllegalArgumentException. for the...

    Java Programming: Hi, I need help Modifying my code that will throw an IllegalArgumentException. for the following data entry error conditions: A number less than 1 or greater than 12 has been entered for the month A negative integer has been entered for the year utilizes a try and catch clause to display an appropriate message when either of these data entry errors exceptions occur. Thank you let me know if you need more info import java.util.*; //Class definition public...

  • ******Java Programming Hi guys, I really need you help. I created a code for my java...

    ******Java Programming Hi guys, I really need you help. I created a code for my java course, but it keep giving me error messages. Majority of my code is fine but some keep display error on my console. I was hoping someone could pin points the problem. .There are three classes with the testCenter class being the main class. In the following is the assignment, and the bottom is my code. Please help! Assignment: Concepts: GUI User Design Graphics Deployment...

  • FOR JAVA: Summary: Create a program that adds students to the class list (see below). The...

    FOR JAVA: Summary: Create a program that adds students to the class list (see below). The solution should be named Roster402_v2.java. Allow the user to control the number of students added to the roster. Ask if the user would like to see their new roster to confirm additions. If yes, then display contents of the file, if no, end the program. ------------------------------------------------------------------------------------- List of student names and IDs for class (this will be your separate text file): Jones, Jim,45 Hicks,...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT