Parsing of math expression gives wrong tree - java

So the code is rather complicated so ill try to do some neat pseudo code that covers the most important issues. I'm trying to parse a math expression. For example: 1-5*(-2)+3 = 14
The syntax that im using is:
expression = term OR term+expression OR term-expression
term = factor OR factor*term OR factor/term
factor = number OR -factor OR (expression)
I have written a piece of code which checks if an expression follows this syntax and it works well for checking the expressions but not for calculating it.
The pseudo code goes something like:
double readExpression()
number = readTerm()
if token == +
number2 = readExpression()
return number + number2
else if token == -
number2 = readExpression()
return number - number2
else
return number
...
(The code for readTerm() is identical to readExpression() in structure)
...
double readFactor()
if token == number
return number
else if token == -
number = readFactor()
return (-1)*number
else if token == (
number = readExpression()
return number
else raise exception
If I do the above calculation with this code it will give me a tree that looks like this:
So anyway, as you matematicians have figured out byt now, the expression should give 14 and not 8 as the tree suggests. I have noticed the that the problem arises when there are minus-signs in front of expressions since affect the whole right term i this problem whilst they should only affect the middle-term.
Ive been thinking like crazy for weeks and thought about solutions for this and looked at other codes and so on. Please dont toss a bunch of links on me if they are not really really simple and good since ive been browsing alot myself on tree traversals and other relevant topics.
What could i do at this stage? As I said, my program can tell if its right or wrong. So now I only need to parse a correct expression. Should I write another class for the parsing of the correct expression? Is it easier? Anyway I dont see how that code would look different than this.

Yes I would parse the equation, it just looks like you miss a key part of the order of operations/parsing. You need to include an additional check for double negatives.
The key factor here is that: In a situation with two identical operators then the left most operation is always carried out first.
First lets narrow down the issue.
This 1-5*(-2)+3 is equal to 1--10+3.
Now for our purposes lets assign a positive to the first operator because it helps illustrate a point:
1--10+3 is the same as +1--10+3
Now if we where to run +1--10+3 through a correct parser we would know that this -- is equal to + but only when used in the following situation:
+X--Y = X+Y
So now our parser has turned the original expression of 1--10+3 into 1+10+3 and we know that is equal to 14.
So all up: Yes you need a parser, but pay special attention to how +X--Y and X+Y work.
Also take a look at this answer: https://stackoverflow.com/a/26227947/1270000

Related

Count how many list entries have a string property that ends with a particular char

I have an array list with some names inside it (first and last names). What I have to do is go through each "first name" and see how many times a character (which the user specifies) shows up at the end of every first name in the array list, and then print out the number of times that character showed up.
public int countFirstName(char c) {
int i = 0;
for (Name n : list) {
if (n.getFirstName().length() - 1 == c) {
i++;
}
}
return i;
}
That is the code I have. The problem is that the counter (i) doesn't add 1 even if there is a character that matches the end of the first name.
You're comparing the index of last character in the string to the required character, instead of the last character itself, which you can access with charAt:
String firstName = n.getFirstName()
if (firstName.charAt(firstName.length() - 1) == c) {
i++;
}
When you're setting out learning to code, there is a great value in using pencil and paper, or describing your algorithm ahead of time, in the language you think in. Most people that learn a foreign language start out by assembling a sentence in their native language, translating it to foreign, then speaking the foreign. Few, if any, learners of a foreign language are able to think in it natively
Coding is no different; all your life you've been speaking English and thinking in it. Now you're aiming to learn a different pattern of thinking, syntax, key words. This task will go a lot easier if you:
work out in high level natural language what you want to do first
write down the steps in clear and simple language, like a recipe
don't try to do too much at once
Had I been a tutor marking your program, id have been looking for something like this:
//method to count the number of list entries ending with a particular character
public int countFirstNamesEndingWith(char lookFor) {
//declare a variable to hold the count
int cnt = 0;
//iterate the list
for (Name n : list) {
//get the first name
String fn = n.getFirstName();
//get the last char of it
char lc = fn.charAt(fn.length() - 1);
//compare
if (lc == lookFor) {
cnt++;
}
}
return cnt;
}
Taking the bullet points in turn:
The comments serve as a high level description of what must be done. We write them aLL first, before even writing a single line of code. My course penalised uncommented code, and writing them first was a handy way of getting the requirement out of the way (they're a chore, right? Not always, but..) but also it is really easy to write a logic algorithm in high level language, then translate the steps into the language learning. I definitely think if you'd taken this approach you wouldn't have made the error you did, as it would have been clear that the code you wrote didn't implement the algorithm you'd have described earlier
Don't try to do too much in one line. Yes, I'm sure plenty of coders think it looks cool, or trick, or shows off what impressive coding smarts they have to pack a good 10 line algorithm into a single line of code that uses some obscure language features but one day it's highly likely that someone else is going to have to come along to maintain that code, improve it or change part of what it does - at that moment it's no longer cool, and it was never really a smart thing to do
Aominee, in their comment, actually gives us something like an example of this:
return (int)list.stream().filter(e -> e.charAt.length()-1)==c).count();
It's a one line implementation of a solution to your problem. Cool huh? Well, it has a bug* (for a start) but it's not the main thrust of my argument. At a more basic level: have you got any idea what it's doing? can you look at it and in 2 seconds tell me how it works?
It's quite an advanced language feature, it's trick for sure, but it might be a very poor solution because it's hard to understand, hard to maintain as a result, and does a lot while looking like a little- it only really makes sense if you're well versed in the language. This one line bundles up a facility that loops over your list, a feature that effectively has a tiny sub method that is called for every item in the list, and whose job is to calculate if the name ends with the sought char
It p's a brilliant feature, a cute example and it surely has its place in production java, but it's place is probably not here, in your learning exercise
Similarly, I'd go as far to say that this line of yours:
if (n.getFirstName().length() - 1 == c) {
Is approaching "doing too much" - I say this because it's where your logic broke down; you didn't write enough code to effectively implement the algorithm. You'd actually have to write even more code to implement this way:
if (n.getFirstName().charAt(n.getFirstName().length() - 1) == c) {
This is a right eyeful to load into your brain and understand. The accepted answer broke it down a bit by first getting the name into a temporary variable. That's a sensible optimisation. I broke it out another step by getting the last char into a temp variable. In a production system I probably wouldn't go that far, but this is your learning phase - try to minimise the number of operations each of your lines does. It will aid your understanding of your own code a great deal
If you do ever get a penchant for writing as much code as possible in as few chars, look at some code golf games here on the stack exchange network; the game is to abuse as many language features as possible to make really short, trick code.. pretty much every winner stands as a testament to condense that should never, ever be put into a production system maintained by normal coders who value their sanity
*the bug is it doesn't get the first name out of the Name object

How to prevent value from changing automatically in java

I'm very new to Java and stackoverflow so I'm sorry if I seem ignorant but I wrote this program to multiply two numbers together using the Russian Peasant multiplication algorithm. The complete program includes far more operations and is hundreds of lines of code but I only included what I thought was necessary for this particular method. I have a test harness so I know that all the submethods work correctly. The problem that I'm struggling with though is the 3rd line where I'm adding factor1 to the product. The values add correctly but then when factor1 is multiplied by 2 in the 5th line then the value that was added to product in the 3rd line also gets doubled resulting in an incorrect product value. How can I make sure that when factor 1 is doubled that it doesn't carry backwards to the product term?
while (Long.parseLong(factor2.toString()) >= 1) {
if (factor2.bigIntArray[0] % 2 == 1) {
product = product.add(factor1);
}
factor1 = factor1.multiplyByTwo();
factor2 = factor2.divideByTwo();
}
I think in your method multiplyByTwo you use code
`datamember=datamember*2;`
rather than that try doing this
return new FactorClass(datamember*2);
so it doesnt change the added value.
it would be better if u could show the mulTiplyByTwo method code since that is where your actually are getting the changed value.

Increment in ternary operator Java

I'm writing small program, and want to get access to an element in array with the loop. And I need to increment "array index" variable for next iteration.
Here is the code:
winner[turn] = subField[(int)Math.floor(i / 10.0)][i % 10].equalsIgnoreCase("O") ? false : winner[turn];
turn++;
Is it possible to make one line of code from it?
PS: I'm trying to write less lines only for myself. It's a training for brain and logic.
Well, it can be done for sure:
winner[turn] = subField[(int)Math.floor(i / 10.0)][i % 10].
equalsIgnoreCase("O") ^ winner[turn++];
Look that there is not even ternary operator there.
But not because it is shorter it is better (and certainly not clearer). So I'd recommend you do it in these many lines:
String aSubField = subField[(int)Math.floor(i / 10.0)][i % 10];
if (aSubField.equalsIgnoreCase("O"))
winner[turn] = false;
turn++;
Look, even there is no need to assign the value in case the comparison yields false.
[edit]
YAY! Just found my XOR was wrong ... that's just the problem with golf, it tooks a lot of time to figure it is wrong .... (in this case, if the cond is true but the previous value is false, it won't work).
So let me golf it other way :)
winner[turn] = !subField[i/10][i%10].equalsIgnoreCase("O") & winner[turn++];
Note the ! and the &
[edit]
Thanks to #Javier for giving me an even more compact and confuse version :) this one:
winner[turn++] &= !subField[i/10][i%10].equalsIgnoreCase("O");
Let's break it down a bit. What you have is:
winner[turn] = (some condition) ? false : (expression involving turn)
(increment turn)
Well, why not increment turn in the array access? That means it'll be incremented by the time you evaluate expressions on the right hand side, but you can easily adjust it back to its previous value as needed.
winner[turn++] = (some condition) ? false : (expression involving (turn - 1) )

How do I effectively use the Modulus Operator in Java

I am doing a college assignment in Java that deals with currency. For that I am advised to use ints instead of doubles and then later convert it to a dollar value when I print out the statement.
Everything works fine until I do calculations on the number 4005 (as in $40.05 represented as an int). I am pasting the part of code I am having problems with, I would appreciate if someone could tell me what I am doing wrong.
import java.io.*;
class modumess {
public static void main(String[] args) {
int money = 4005; //Amount in cents, so $40.05;
// Represent as normal currency
System.out.printf("$%d.%d", money/100, money%100);
}
}
The above code, when run, shows $40.5, instead of $40.05. What gives?
Kindly note that this is for my homework and I want to learn, so I would really appreciate an explanation about the root of the problem here rather than just a simple solution.
EDIT: Following Finbarr's answer, I have added the following to the code which seems to have fixed the problem:
if (money%100 < 10) {
format = "$%d.0%d";
}
Is this a good way to do it or am I over-complicating things here?
EDIT: I just want to make it clear that it was both Finbarr and Wes's answer that helped me, I accepted Wes's answer because it made it clearer for me on how to proceed.
A better way would be something like this for a general case:
format = "%d.%02d";
%02d gives you 0 padding for 2 digits. That way you don't need the extra if statement.
See this for more explanation of things you can do in format: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax
The modulus operator returns the remainder after division without fractional calculation. In this case, 4005%100 returns 5 as the remainder of 4005/100 is 5.

Unexplained parenthesise in Java

What do parenthesis do in Java other than type casting.
I've seen them used in a number of confusing situations, here's one from the Java Tutorials:
//convert strings to numbers
float a = (Float.valueOf(args[0]) ).floatValue();
float b = (Float.valueOf(args[1]) ).floatValue();
I only know only two uses for parenthesis, calls, and grouping expressions. I have searched the web but I can't find any more information.
In the example above I know Float.valueOF(arg) returns an object. What effect does parenthesize-ing the object have?
Absolutely nothing. In this case they are not necessary and can be removed. They are most likely there to make it more clear that floatValue() is called after Float.valueOf().
So this is a case of parenthesis used to group expressions. Here it's grouping a single expression (which does obviously nothing).
It can be shortened to:
float a = Float.valueOf(args[0]).floatValue();
float b = Float.valueOf(args[1]).floatValue();
which can then be logically shortened to
float a = Float.parseFloat(args[0]);
float b = Float.parseFloat(args[1]);
I dont believe they serve any purpose here. Maybe left over after some refactoring
None other than to confuse you. It's as good as saying
float a = Float.valueOf(args[0]).floatValue();
directly.
I suspect the programmer just found it more readable. I don't agree with him in this particular case, but often use parentheses to make it clearer. For example, I find
int i = 3 + (2 * 4);
clearer than
int i = 3 + 2 * 4;
The extra parentheses in your code sample do not add anything.
//Your example:
float a = (Float.valueOf(args[0]) ).floatValue();
// equivalent:
float a = Float.valueOf(args[0]).floatValue();
It could be that the original programmer had done something more elaborate within the parentheses and so had them for grouping, and neglected to remove them when simplifying the code. But trying to read intent into old source is an exercise in futility.
The extra space in args[0]) ) is pretty odd looking, too, as it is unmatched in the opening paren.
Here they are used for grouping. What's inside one of those expression if of type Float, so you can apply the method floatValue() to the whole content of the parenthesis.
They could be removed here as there is no ambiguity. They would have been mandatory with an expression using another operator of higher preseance order. But according to the docs, there is no such operator, the dot/projector has highest priority. So they are really useless here.
Regards,
Stéphane

Categories

Resources