# Thread: Need help on a calculator project

1. Member
Join Date
Feb 2012
Posts
26
Rep Power
0

## Need help on a calculator project

So far, I have addition, subtraction, multiplication and division implemented. There can be spaces between the numbers and the math symbols. Negative numbers are allowed, and an unlimited number of symbols are allowed per expression. Log can be entered to start logging the equations entered and the answers given, either until log off is entered or the program quits by entering quit. If something other than an expression, "quit", "log" or "log off" is entered, an error will be displayed instead of the program crashing.

What I want to implement is assigning numbers to variables (either x, y, or z).

Some examples:

? x = 27.8 / 5.2
→ 5.346
? y = 100.5 − x *2
→ 89.807
? x
→ 5.346
? z = x − 80 * −2 + 20
→ 185.346

So, for example x starts out with a value of zero, if I enter x = 27.8 / 5.2 x will now have a value of 5.346 until I quit the program or assign x to a new number.

Where do I start with this? I figure I need to start by adding a new layer that the program will go even lower than the negative sign to that includes the equal sign.

Here is what I have so far (two files, Calculator.java and ExpressionDialog.java):

Java Code:
```public class Calculator
{
String expstring;
int cursor;

public Calculator()
{
expstring = null;
}

public Calculator(String instring)
{
expstring = instring;
cursor = 0;
}

public void setExpression(String estring)
{
expstring = estring;
cursor = 0;
}

public float evalExp()
{
if (expstring == null)
{
System.err.println("There is no expression to evaluate.");
System.err.println("Call setExpression() before calling getResult().");
return 0;
}
cursor = 0;
float result = evalTerm();
while (nextOperator('+'))
{
char operator = getOperator();
float term = evalTerm();
if (operator == '+')
result = result + term;
else
System.err.println("Invalid operator: " + operator);
}
while (nextOperator('-'))
{
char operator = getOperator();
float term = evalTerm();
if (operator == '-')
result = result - term;
else
System.err.println("Invalid operator: " + operator);
}
return result;
}

private float evalTerm()
{
float result = getOperand();
while (nextOperator('*'))
{
char operator = getOperator();
float term = getOperand();
if (operator == '*')
result = result * term;
else
break;
}
while (nextOperator('/'))
{
char operator = getOperator();
float term = getOperand();
if (operator == '/')
result = result / term;
else
break;
}
return result;
}

private float getOperand()
{
if (cursor >= expstring.length())
return 0;
String opstring = "";
char nextchar = expstring.charAt(cursor);
if (nextchar == '-')
{
opstring = opstring + '-';
cursor++;
nextchar = expstring.charAt(cursor);
}
while (cursor < expstring.length() && !isOperator(nextchar))
{
opstring = opstring + nextchar;
cursor++;
if (cursor < expstring.length())
nextchar = expstring.charAt(cursor);
}
return Float.parseFloat(opstring);
}

private char getOperator()
{
char operator = expstring.charAt(cursor);
cursor++;
return operator;
}

private boolean nextOperator(char op)
{
if (cursor < expstring.length() && expstring.charAt(cursor) == op)
return true;
else
return false;
}

private boolean isOperator(char c)
{
String opset = "+*-/";
return (opset.indexOf(c) >= 0);
}
}```
Java Code:
```import java.util.*;
import java.io.*;

class ExpressionDialog
{
Calculator calc;
PrintStream logfile;

public ExpressionDialog()
{
calc = new Calculator();
}

public void run()
{
String expression;
float result = 0;
expression = getNextExpression();
while(!expression.equals("quit"))
{
if (expression.equals("log off") && (logfile != null))
{
logfile.close();
}
else if (expression.equals("log"))
{
//Not very clean, prompt should be on the same line as the user input
//Also adds a space and => 0.0 at the start of the file, this isn't clean and ideally should be changed
System.out.println("Enter in a filename");
}
else
{
calc.setExpression(expression);
try
{
result = calc.evalExp();
System.out.println("=> " + result);
if (logfile != null)
{
logfile.println(expression);
logfile.println("=> " + result);
}
}
catch (NumberFormatException e)
{
System.out.println("Incorrect entry");
}
}
expression = getNextExpression();
}
if (logfile != null)
logfile.close();
}

private String getNextExpression()
{
System.out.print("? ");
}

{
System.out.println("<expression>      //Enter a simple arithmetic expression");
System.out.println("log <filename>    //Turn on file logging to the specified output file");
System.out.println("log off           //Turn file logging off");
System.out.println("quit              //To terminate the program");
}

private void setLogFile(String filename)
{
try
{
logfile = new PrintStream(filename);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}

public static void main(String[] args)
{
ExpressionDialog dialog = new ExpressionDialog();
if (args.length > 0)
dialog.setLogFile(args[0]);
dialog.run();
}
}```

2. ## Re: Need help on a calculator project

Do you have any specific questions or problems?

3. Member
Join Date
Feb 2012
Posts
26
Rep Power
0

## Re: Need help on a calculator project

Yeah, sorry if I wasn't specific. I'm just not sure where to start to implement an equal sign and variables.

Is that not really what this forum is for? I mean, I was kind of wondering if this was a specific question forum or general programming help forum.
Last edited by Speculant; 02-03-2012 at 02:32 AM.

4. ## Re: Need help on a calculator project

specific question forum or general programming help forum.
Not sure what the difference is.
We'll help you fix your code. You say what the problems are and we'll make suggestions on how to fix them.

where to start to implement an equal sign
By equal sign I assume you mean an assignment statement.
Before the = is the variable to receive the value.
Fpllowing the = is the expression whose value is to be placed into the variable to the left of the =

One way to save the variable would be in a Map with the key being the variable's name and its value being its value.

5. ## Re: Need help on a calculator project

I once wrote an article for the blogs on this forum about expression compilation, including working code. You might have a read; you can do with the code whatever you want. The compiler comes with a few back-ends: a pure interpreter and a code generator, each with its pros and cons.

kind regards,

Jos

6. Member
Join Date
Oct 2011
Posts
92
Rep Power
0

## Re: Need help on a calculator project

Sounds to me, for the variable assignment deal you want to implement a hash map for the solution. An assignment is a binary operator. So if the user types in:

x = 10

You've got your key, "x", and your value, 10. Whenever you need the value of X, you just look up x in the hashmap and it gives you back it's value. I can see what you are thinking, in terms of generating code to ACTUALLY store variables with the values that the user enters. But ultimately there is no difference to the user's experience if you just use a hashmap. Values a still being stored in memory one way or the other, I just imagine that implementing a hashmap to store the values might be a little more efficient than making new code alltogether :)

7. ## Re: Need help on a calculator project

If the parser sees an 'x' it can not blindly generate code for the value of 'x'. It has to know whether or not to create code for the lhs (left hand side) of 'x' or just the rhs (right hand side). See my blog article how it can be done.

kind regards,

Jos

8. Member
Join Date
Feb 2012
Posts
26
Rep Power
0

## Re: Need help on a calculator project

Jos, I can't read your blog entry. A forum message says I don't have proper privileges.

9. ## Re: Need help on a calculator project

Originally Posted by Speculant
Jos, I can't read your blog entry. A forum message says I don't have proper privileges.
I see what I can do about it; in the mean time, keep on trying. I can't send the stuff to you through PM. I'll check with the gods of the forum.

kind regards,

Jos

10. Member
Join Date
Feb 2012
Posts
26
Rep Power
0

## Re: Need help on a calculator project

Is there a way to do this without using a hashmap?

11. ## Re: Need help on a calculator project

Sure, there are always ways to do it, but they will be awkward and difficult.
A Map is a natural fit. Given a variable name, you can easily retrieve its value.

12. Member
Join Date
Feb 2012
Posts
26
Rep Power
0

## Re: Need help on a calculator project

Here is my modified Calculator.java

I'm getting an error on line 30, HashMap cannot be resolved to a type. How do I fix this?

Java Code:
```public class Calculator
{
String expstring;
int cursor;
float x = 0;
float y = 0;
float z = 0;

public Calculator()
{
expstring = null;
}

public Calculator(String instring)
{
expstring = instring;
cursor = 0;
}

public void setExpression(String estring)
{
expstring = estring;
cursor = 0;
}

public float assignmentOp()
{
cursor = 0;
HashMap hashMap = new HashMap();
float result = evalExp();
while (nextOperator('='))
{
char operator = getOperator();
float term = evalExp();
if (operator == '=')
hashMap.put(result, term);
else
System.err.println("Only variables x, y or z may be allowed to be assigned.");
}
return result;
}

public float evalExp()
{
if (expstring == null)
{
System.err.println("There is no expression to evaluate.");
System.err.println("Call setExpression() before calling getResult().");
return 0;
}

float result = evalTerm();
while (nextOperator('+'))
{
char operator = getOperator();
float term = evalTerm();
if (operator == '+')
result = result + term;
else
System.err.println("Invalid operator: " + operator);
}
while (nextOperator('-'))
{
char operator = getOperator();
float term = evalTerm();
if (operator == '-')
result = result - term;
else
System.err.println("Invalid operator: " + operator);
}
return result;
}

private float evalTerm()
{
float result = getOperand();
while (nextOperator('*'))
{
char operator = getOperator();
float term = getOperand();
if (operator == '*')
result = result * term;
else
break;
}
while (nextOperator('/'))
{
char operator = getOperator();
float term = getOperand();
if (operator == '/')
result = result / term;
else
break;
}
return result;
}

private float getOperand()
{
if (cursor >= expstring.length())
return 0;
String opstring = "";
char nextchar = expstring.charAt(cursor);
if (nextchar == '-')
{
opstring = opstring + '-';
cursor++;
nextchar = expstring.charAt(cursor);
}
while (cursor < expstring.length() && !isOperator(nextchar))
{
opstring = opstring + nextchar;
cursor++;
if (cursor < expstring.length())
nextchar = expstring.charAt(cursor);
}
return Float.parseFloat(opstring);
}

private char getOperator()
{
char operator = expstring.charAt(cursor);
cursor++;
return operator;
}

private boolean nextOperator(char op)
{
if (cursor < expstring.length() && expstring.charAt(cursor) == op)
return true;
else
return false;
}

private boolean isOperator(char c)
{
String opset = "+*-/=xyz";
return (opset.indexOf(c) >= 0);
}
}```

13. ## Re: Need help on a calculator project

Is it working the way you want now?

14. Member
Join Date
Feb 2012
Posts
26
Rep Power
0

## Re: Need help on a calculator project

Sorry, I edited my post.

15. Member
Join Date
Feb 2012
Posts
26
Rep Power
0

## Re: Need help on a calculator project

I used import java.util.* and the "HashMap cannot be resolved to a type" error went away, but now I am getting a warning:

"java.util.HashMap is a raw type. References to generic type java.util.HashMap<K,V> should be parameterized"

Where in my code do I place the "HashMap hashMap = new HashMap()" line to prevent this error?

16. ## Re: Need help on a calculator project

That message is a warning that you are not using the Generics <K,V> part of the class's definition. You can ignore it or you can study how to use Generics in defining your class.
http://docs.oracle.com/javase/tutori...ics/index.html
Last edited by Norm; 02-06-2012 at 07:51 PM.

17. Member
Join Date
Feb 2012
Posts
26
Rep Power
0

## Re: Need help on a calculator project

I changed assignmentOp in Calculator.java to give the user an error statement if they try to assign a value to a key that isn't x, y, or z. I also moved float x = 0, float y = 0, and float z = 0 to ExpressionDialog.java, but how to I pass x, y, and z to assignmentOp from ExpressionDialog? Right now, I'm getting an error that x, y, and z referenced in Calculator.java can't be assigned to variables.

Java Code:
```import java.util.*;
import java.io.*;

class ExpressionDialog
{
Calculator calc;
PrintStream logfile;
HashMap hashMap = new HashMap();
float x = 0;
float y = 0;
float z = 0;

public ExpressionDialog()
{
calc = new Calculator();
}

public void run()
{
String expression;
float result = 0;
expression = getNextExpression();
while(!expression.equals("quit"))
{
if (expression.equals("log off") && (logfile != null))
{
logfile.close();
}
else if (expression.equals("log"))
{
//Not very clean, prompt should be on the same line as the user input
//Also adds a space and => 0.0 at the start of the file, this isn't clean and ideally should be changed
System.out.println("Enter in a filename");
}
else if (expression.equals("x"))
{
hashMap.get(x);
}
else if (expression.equals("y"))
{
hashMap.get(y);
}
else if (expression.equals("z"))
{
hashMap.get(z);
}
else
{
calc.setExpression(expression);
try
{
result = calc.assignmentOp(hashMap);
System.out.println("=> " + result);
if (logfile != null)
{
logfile.println(expression);
logfile.println("=> " + result);
}
}
catch (NumberFormatException e)
{
System.out.println("Incorrect entry");
}
}
expression = getNextExpression();
}
if (logfile != null)
logfile.close();
}

private String getNextExpression()
{
System.out.print("? ");
}

{
System.out.println("<expression>      //Enter a simple arithmetic expression");
System.out.println("log <filename>    //Turn on file logging to the specified output file");
System.out.println("log off           //Turn file logging off");
System.out.println("quit              //To terminate the program");
}

private void setLogFile(String filename)
{
try
{
logfile = new PrintStream(filename);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}

public static void main(String[] args)
{
ExpressionDialog dialog = new ExpressionDialog();
if (args.length > 0)
dialog.setLogFile(args[0]);
dialog.run();
}
}```
Java Code:
```import java.util.*;
public class Calculator
{
String expstring;
int cursor;

public Calculator()
{
expstring = null;
}

public Calculator(String instring)
{
expstring = instring;
cursor = 0;
}

public void setExpression(String estring)
{
expstring = estring;
cursor = 0;
}

public float assignmentOp(HashMap hashMap)
{
cursor = 0;
float result = evalExp();
while (nextOperator('='))
{
char operator = getOperator();
float term = evalExp();
if (operator == '=' && result == x || result == y || result == z)
hashMap.put(result, term);
else
System.err.println("Only variables x, y or z may be allowed to be assigned.");
}
return result;
}

public float evalExp()
{
if (expstring == null)
{
System.err.println("There is no expression to evaluate.");
System.err.println("Call setExpression() before calling getResult().");
return 0;
}

float result = evalTerm();
while (nextOperator('+'))
{
char operator = getOperator();
float term = evalTerm();
if (operator == '+')
result = result + term;
else
System.err.println("Invalid operator: " + operator);
}
while (nextOperator('-'))
{
char operator = getOperator();
float term = evalTerm();
if (operator == '-')
result = result - term;
else
System.err.println("Invalid operator: " + operator);
}
return result;
}

private float evalTerm()
{
float result = getOperand();
while (nextOperator('*'))
{
char operator = getOperator();
float term = getOperand();
if (operator == '*')
result = result * term;
else
break;
}
while (nextOperator('/'))
{
char operator = getOperator();
float term = getOperand();
if (operator == '/')
result = result / term;
else
break;
}
return result;
}

private float getOperand()
{
if (cursor >= expstring.length())
return 0;
String opstring = "";
char nextchar = expstring.charAt(cursor);
if (nextchar == '-')
{
opstring = opstring + '-';
cursor++;
nextchar = expstring.charAt(cursor);
}
while (cursor < expstring.length() && !isOperator(nextchar))
{
opstring = opstring + nextchar;
cursor++;
if (cursor < expstring.length())
nextchar = expstring.charAt(cursor);
}
return Float.parseFloat(opstring);
}

private char getOperator()
{
char operator = expstring.charAt(cursor);
cursor++;
return operator;
}

private boolean nextOperator(char op)
{
if (cursor < expstring.length() && expstring.charAt(cursor) == op)
return true;
else
return false;
}

private boolean isOperator(char c)
{
String opset = "+*-/=xyz";
return (opset.indexOf(c) >= 0);
}
}```

18. ## Re: Need help on a calculator project

getting an error that x, y, and z referenced in Calculator.java can't be assigned to variables.
Please post the full text of the error messages.

Where are those three variables defined?

19. Member
Join Date
Feb 2012
Posts
26
Rep Power
0

## Re: Need help on a calculator project

Error: x cannot be resolved to a variable
Error: y cannot be resolved to a variable
Error: z cannot be resolved to a variable

They are defined at the start of ExpressionDialog

20. ## Re: Need help on a calculator project

Variables defined in one class are NOT known in other classes without special coding that shows where the variables are defined.
If you want to have/use the variables in Calculator, you must define them there or get a reference to the ExpressionDialog class object and use it to access them there.

Page 1 of 3 123 Last

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•