Simple Calculator problem, not reading in answer [duplicate] - java

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Making a simple calculator cannot exit loop or give answer
hi, so basically my code at the moment takes the last value in and does the calculation with the same number
so
5+6=12
how can i store the operands and then use them in the calculation
public double getResult(){
if (getOperator() == '+')
{
result = (getOperand() + getOperand());
}
if (getOperator() == '-')
{
result = (getOperand() - getOperand());
}
if (getOperator() == '*')
{
result = (getOperand() * getOperand());
}
if (getOperator() == '/')
{
result = (getOperand() / getOperand());
}
return result;
}
public boolean getanswer(String value)
{
boolean isnum = false;
try {
setOperand(Double.parseDouble(value));
operand = (Double.parseDouble(value));
getResult();
isnum = true;
}
catch(Exception e)
{
try {
setOperator(value.charAt(0));
operator = (value.charAt(0));
isnum = false;
}
catch(Exception e2)
{
System.out.println("Enter a number");
}

You may restructure your program as follows to get what you want:
read first operand and save into variable operand1
read operator and save into variable operator
read second operand and save into variable operand
perform calculation result = operand1 operator operand2
If you want to loop this one you can add another step: 5. replace operand1 with result and goto 2.
In your design to try to do this within a single calculator class. Since you do not have the "main" loop in there you somehow have to save the state you are currently in (i.e. something like the step number of the algorithm). This would result in something like:
if i'm in state 1 and an operand is coming in: save in variable operand1 and update state variable to 2.
if i'm in state 2 and an operator is coming in: save in variable operator and update state variable to 3.
...

Related

Error: Unreachable code [duplicate]

This question already has answers here:
Unreachable code compiler error [duplicate]
(7 answers)
Closed 6 years ago.
Why does this method return the error: Error: Unreachable code Thank you!
public static boolean zeroCheck(double numberTwo, String operator) {
if (numberTwo == 0) {
return false;
if(operator == "/" || operator == "%")
System.out.println("You cannot use a zero to divide or mod.");
} else return true;
}
}
Error:
File: C:\JAVA\LABS\LabSix.java [line: 228]
Error: Unreachable code
You return a value before you procceed to the rest of the code that is never reached. When you use the return statement, it automatically ends the code and returns boolean in your case.
Just put your return statement in the end of your block.
public static boolean zeroCheck(double numberTwo, String operator) {
if (numberTwo == 0) {
if (operator == "/" || operator == "%") {
System.out.println("You cannot use a zero to divide or mod.");
}
return false;
} else return true
}
By the way, if you want to compare String, please use equals(..) method, because String is not the primitive type like int or double etc. are. Generally, use equals(..) in case of comparing all objects.
if (operator.equals("/") || operator.equals("%"))
I'm assuming you meant to put the return false after the operator check. What happens is that the function returns when the numberTwo is 0 before the code gets a chance to check the if statement, making this the unreachable code
Don't worry, this is a common misunderstanding for newcomers, it's not just you. :-) The return keyword does two things:
Determines what the return value of the function will be, and
Exits the function at that point
Newcomers sometimes think it just does the first, not the second. (And there are languages where the two are in fact done separately, Java just isn't one of them.)
So in your example, the unreachable code is the code after the return false;, since when the return false; statement is executed, it exits the function.
Just put it after the other code in that block:
public static boolean zeroCheck(double numberTwo, String operator)
{
if (numberTwo == 0)
{
if (operator.equals("/") || operator.equals("%"))
{
System.out.println("You cannot use a zero to divide or mod.");
}
return false;
}
else // See note #3 below, you don't really need this
{
return true;
}
}
A couple of other notes on the code above:
You don't compare strings in Java with ==, you use str.equals(otherStr). More: How do I compare strings in Java?
Note that I added braces around the inner block (the one attached to if (operator.equals...). They aren't strictly-speaking necessary, but when you're using braces in the outer block (which you have to), leaving them off the inner block can trip up someone editing the code later.
Since your if block ends with return false;, there's no need for the else; you could just follow the end of the if block with return true; It can't be reached if you went into the block, because of course, you exited the function.
The code above returns false if numberTwo is 0, even if the operator isn't / or %. That's what I think your original code meant to do, but I thought I'd flag it up.
Re #3 above, another option is to remember your return value in a variable:
public static boolean zeroCheck(double numberTwo, String operator)
{
boolean numberTwoIsZero = numberTwo == 0;
if (numberTwoIsZero)
{
if (operator.equals("/") || operator.equals("%"))
{
System.out.println("You cannot use a zero to divide or mod.");
}
}
return numberTwoIsZero;
}

Java Postfix char to String conversion

Using BlueJ to write the code and jUnit to test it out.
Trying to convert a infixToPostfix class I have from my lab class from using char to using strings. This would make it so instead of being limited to single input of say "ab+c-d*-" of char's, it would be able to read "a b + c - d * -"
It's working with a stack which is fairly new to me and I have no idea how exactly I'd go about this. The code I have so far is:
public class InfixToPostfix
{
private Stack operators = new Stack();
/**
* Constructor for objects of class InfixToPostfix
*/
public InfixToPostfix()
{
}
/**
* toPostfix
*/
public String toPostfix(String infix)
{
String [] tokens = new String[100];
int i;
int length = infix.length();
String operator;
String output = "";
for (i = 0; i < length; i++)
{
if (isOperator(tokens[i]))
if (operators.empty())
// 2. If the stack is empty, push the incoming operator onto the stack.
operators.push(tokens[i] + " ");
else
{
if (operatorLessPrecedence(tokens[i]))
// 3. If the incoming symbol has equal or lower precedence than the
// symbol on the top of the stack, pop the stack and print the top
// operator. Then test the incoming operator against the new top of stack.
// Push the incoming symbol onto the stack.
{
do
{
output = output + operators.pop();
}
while (!operators.empty() && operatorLessPrecedence(tokens[i]));
operators.push(tokens[i] + " ");
}
else
// 4. If the incoming symbol has higher precedence than the top of the stack,
// push it on the stack.
operators.push(tokens[i]);
}
else
// 1. Print operands as they arrive.
output = output + tokens[i] + " ";
}
while (!operators.empty())
{
// 5. At the end of the expression, pop and print all operators on the stack.
operator = (String)operators.pop();
output = output + operator + " ";
}
return output;
}
/**
* isOperator
*/
public boolean isOperator(String c)
{
if( c.equals("/") ||
c.equals("'") ||
c.equals("+") ||
c.equals("-"))
return true;
else
return false;
}
/**
* operatorLessPrecedence
* Compare operator with top of stack
* Assume association left to right
*/
public boolean operatorLessPrecedence(String o)
{
int operatorPrecedence = precedence(o);
int tosPrecedence = precedence((String)operators.peek());
return (operatorPrecedence <= tosPrecedence);
}
/**
* precedence
*/
public int precedence(String o)
{
switch (o)
{
case "+": return 1;
case "-": return 1;
case "*": return 2;
case "/": return 2;
}
return 5;
}
}
So when I test in jUnit using a assertEquals;
#Test
public void testAddSub()
{
InfixToPostfix test = new InfixToPostfix();
assertEquals("1 2 +", test.toPostfix("1 + 2"));
assertEquals("2 1 -", test.toPostfix("2 - 1"));
}
I get an exception method currently, before i changed the isOperator method from "==" which was used for testing char's to what I thought was correct, the .equals() method to test strings, I would only get null outputs..
I don't want a straight up code or what exactly I'm doing wrong, just a "forceful" nudge in the right direction or something I can look into. Thanks.
An array of objects holds a reference to the object. When you initialized the array, you just allocated the memory for 100 empty spots. You have to put some real Strings objects on it, otherwise NullPointerException 'll be your output.
So, in your line
String [] tokens = new String[100];
You have an array of 100 Strings references which values are null.
The correct way to compare String objects is using equals method.
Using == you'll test object references, equals tests the String value. So, don't change your method implementation, you are in the right path.
I don't recommend the use of Stack object. As you stated that Stack is a new thing for you and you are trying to improve, I would recommend that you take a look at this discussion if you have time available and get your own conclusion.
Why should I use Deque over Stack?.

How this type of expression works [duplicate]

This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 7 years ago.
Can anybody tell me how the snippet below will be executed?
Code:-
int a = 3, b = 4;
a = (a > b) ? a : b;
System.out.print(a);
It is the same as
int a = 3;
int b = 4;
if(a > b) {
a = a;
} else {
a = b;
}
System.out.print(a);
Also see
What is the Java ?: operator called and what does it do?
This is a ternary operator (note: not particular to Java but it's widespread and implemented in many languages), and returns either the 2nd or 3rd argument depending on the result of the initial condition.
result = condition ? result if true : result if false
and as such it's shorthand for
if (condition) {
return a;
}
else {
return b;
}
The value of a variable often depends on whether a particular boolean expression is or is not true and on nothing else. For instance one common operation is setting the value of a variable to the maximum of two quantities. In Java you might write
if (a > b) {
max = a;
}
else {
max = b;
}
Setting a single variable to one of two states based on a single condition is such a common use of if-else that a shortcut has been devised for it, the conditional operator, ?:. Using the conditional operator you can rewrite the above example in a single line like this:
max = (a > b) ? a : b;
(a > b) ? a : b; is an expression which returns one of two values, a or b. The condition, (a > b), is tested. If it is true the first value, a, is returned. If it is false, the second value, b, is returned. Whichever value is returned is dependent on the conditional test, a > b. The condition can be any expression which returns a boolean value.
line 1: a and b are defined.
line 2: a is set to the value of b (because 3 is not bigger than 4).
line 3: a is printed to current std out.
If 'a' is greater than 'b' you'll get a = a, otherwise if 'b' is greater than 'a' you'll get a = b.
It is the same as the following:
int a = 3, b = 4;
if(a > b){
a = a;
}else{
a = b;
}
System.out.print(a);
And that could be rewritten as:
int a = 3, b = 4;
if(a <= b){
a = b;
}
System.out.print(a);
The ? is the ternary operator, which considers the code before as condition and evaluates the code before the : is it is true, and the code after : if it is false.

In regards to continues subtraction

I made a swing calculator as part of homework that I did and would like some advice on continues subtraction in particular.
With continues adding up it is straight forward enough(i.o.w. adding the operands and then to continue adding from there onwards). This is what I did.
if(totalCount > 1)
{
if(sbOne.length() > 0)
{
operandOne = Double.parseDouble(sbOne.toString());
}
else
{
operandOne = 0;
}
if(sbTwo.length() > 0)
{
operandTwo = Double.parseDouble(sbTwo.toString());
}
else
{
operandTwo = 0;
}
result = operandOne + operandTwo;
totalResult += result;
screenResult = Double.toString(totalResult);
txtDisplay.setText(screenResult);
notCalculate = true;
sbOne.setLength(0);
sbTwo.setLength(0);
How can I achieve the same result by subtracting one operand from another and then to continue subtracting from there onwards.
Your code seems confusing, particularly as it is incomplete and not compilable. My interpretation of your code is as follows: you have two presumably positive values which you add together, whereupon you add that sum to a total which you already have. My interpretation of your question is as follows: you want to subtract that sum from the total. A solution to that is as Hot Licks said, which is just to use the following operation: totalResult -= result;. If you want to make it possible to decide whether or not you want to add or subtract, add a Boolean flag, namely:
/*somewhere in your code to determine whether you add or subtract,
have a button or something which changes this value.
*/
boolean isAdding = true;
//...
//button pressed
isAdding = false;
//...
//your calculating code goes here
if(isAdding)
totalResult += result;
else
totalResult -= result;
//all of the other stuff

First Java program (calculator) problems

I'm in the process of learning Java and my first project is a calculator, however I've run into a snag. I'm trying to get my calculator to let me enter a number then click an operator (+, -, x, /), enter another number then hit an operator again and have the display update and be able to keep this going.
Example, I would like to be able to hit the following and have it display the total each time I hit an operator after the first:
a + b / c - d =
The code I have seems (to me) like it should work but it doesn't. What am I doing wrong?
The following is the code I'm using when you hit an operator. By default wait is set to false. After running through the class once, value1 is stored and wait is set to true and that works fine. From there it doesn't seem to work quite right:
class OperatorListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String input = event.getActionCommand();
// Set display as string
String s = display.getText();
if (!wait) {
// Convert first input string to double
try {
value1 = Double.valueOf(s.trim()).doubleValue();
} catch (NumberFormatException nfe) {
System.out.println("NumberFormatException: " + nfe.getMessage());
}
dec = false;
} else {
// Convert second input string to double
try {
value2 = Double.valueOf(s.trim()).doubleValue();
} catch (NumberFormatException nfe) {
System.out.println("NumberFormatException: " + nfe.getMessage());
}
// Determine operation to be performed
if (operator == "add") {
value1 = Operators.add(value1, value2);
} else if (operator == "subtract") {
value1 = Operators.subtract(value1, value2);
} else if (operator == "multiply") {
value1 = Operators.multiply(value1, value2);
} else if (operator == "divide") {
value1 = Operators.divide(value1, value2);
}
// Convert final value to string and display
display.setText(Double.toString(value1));
dec = false;
}
// Determine operator hit
if (input.equals("+")) {
operator = "add";
} else if (input.equals("-")) {
operator = "subtract";
} else if (input.equals("x")) {
operator = "multiply";
} else if (input.equals("/")) {
operator = "divide";
}
// Set wait
wait = true;
}
}
EDIT: Updated code to fix some confusion and update the if statement. Even after this the same problem still exists. Also, the full source is available here
A few suggestions.
First, I would suggest when using a boolean as a conditional for an if statement, avoid comparison with true and false -- there are only two states for boolean anyway. Also, since there are only two states, rather than using else if (false), an else will suffice:
if (condition == true)
{
// when condition is true
}
else if (condition == false)
{
// when condition is false
}
can be rewritten as:
if (condition)
{
// when condition is true
}
else
{
// when condition is false
}
Second, rather than comparing the string literals "add", "subtract" and such, try to use constants (final variables), or enums. Doing a String comparison such as (operator == "add") is performing a check to see whether the string literal "add" and the operator variable are both refering to the same object, not whether the values are the same. So under certain circumstances, you may have the operator set to "add" but the comparison may not be true because the string literal is refering to a separate object. A simple workaround would be:
final String operatorAdd = "add";
// ...
if (input.equals("+"))
operator = operatorAdd;
// ...
if (operator == operatorAdd)
// ...
Now, both the assignment of operator and the comparison of operator both are referecing the constant operatorAdd, so the comparison can use a == rather than a equals() method.
Third, as this seems like the type of calculator which doesn't really require two operands (i.e. operand1 + operand2), but rather a single operand which is acting upon a stored value (i.e. operand + currentValue), it probably would be easier to have some variable that holds the current value, and another variable that holds the operator, and a method which will act according to the current operator and operand. (More or less an idea of an accumulator machine, or 1-operand computer.)
The basic method of operation will be:
Set the currentValue.
Set the operator.
Set the operand.
Perform the calculation.
Set the currentValue to the result of the calculation.
Set the operator to blank state.
Each step should check that the previous step took place -- be sure that an operation is specified (operator is set to a valid operator), then the next value entered becomes the operand. A calculator is like a state machine, where going from one step to another must be performed in a certain order, or else it will not proceed to the next step.
So, the calculator may be like this (pseudocode!):
// Initialize calculator (Step 1)
currentValue = 0;
operand = 0;
operator = operatorNone;
loop
{
operand = getOperand(); // Step 2
operator = getOperator(); // Step 3
// Step 4 and 5
if (operator == operatorAdd)
currentValue += operand;
if (operator == operatorSubtract)
currentValue -= operand;
// ...
// Step 6
operator = operatorNone;
}
Although the above code uses a single loop and doesn't work like a event-based GUI model, but it should outline the steps that it takes to run a calculator.
Whenever you enter an operator, your code will execute this:
Double.valueOf(s.trim())
for setting either value1 or value2 (depending on wait). This will throw an exception because operators can't be parsed as doubles. You might have better luck checking for the operator first, before trying to parse the input as a number. Then if it was an operator, you can skip the number parsing part.
Also consider what might happen if somebody were to enter two numbers or two operators in a row.
As Greg said, no matter what the input and no matter what the current program state, you always parse out number. You need to track the program state more cleanly. I assume that when you code has "String s = output.getText();" that you really mean "String s = input.getText();".
Also note that
if (wait == false) {
// Stuff for !wait
} else if (wait == true) {
// Stuff for wait
}
is unnecessarily redundant. You can replace it with:
if (!wait) {
// Stuff for !wait
} else {
// Stuff for wait
}
You should probably check the input string to see if it is an operator, first, and if it isn't then make sure it is numeric. Writing an infix calculator (that properly handles precedence) is not trivial.
After searching high and low I finally determined that the problem didn't lie within the code I provided. I had had a "wait = false;" in my NumberListener class that was screwing up the execution. To solve this I created 2 separate wait variables and all is working fine so far.
Thanks for the help and the tips guys, +1 to all of you for trying.
You could use the scripting engine in Java. If you don't have Java 6+, you can use Rhino which does the same thing. You can then do pretty much anything you can do in JavaScript
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create a JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
// expose a, b, c, d
engine.put("a", 1);
engine.put("b", 8);
engine.put("c", 2);
engine.put("d", 3);
// evaluate JavaScript code from String
Number value = (Number) engine.eval("a + b / c * d");
System.out.println(value);
For more examples

Categories

Resources