Invalid Assignment Operator java - java

Here is my code:
h[ht] * sth -= 3;
the " * " gives me an error:
Syntax error on token "*", invalid AssignmentOperator
I need the value of h[ht]*sth to be reduced by 3

Your example is invalid because "-=" is actually a contracted form:
int a = 1;
a -= 1;
// the above line is the same as:
a = a - 1
Assign the computation to something else:
int a = (h[ht] * sth) - 3

what you are trying is syntactically incorrect.
I suppose h[ht] and sth are two different variables and you want to reduce their result by 3.
basically this is Compile time error, therefore this not able to compile. Right?
in order to achieve this you need to break it into two different statements i.e.
int/long/float/double temp = h[ht] * sth;
temp-=3;
or you can achieve this like this also ( h[ht] * sth )-3
and you will able to achieve what you want to do.
Please read here. and let me tell you Java's compiler is implemented using this grammar, therefore if any statement is not following these grammatical rules, result into syntactical error.
I hope your issue will be resolved.
Thank you

Related

Why does IntelliJ wants me to change this?

A simple line of code:
String thing = "Something";
thing += " something else" + " and more.";
IntelliJ IDEA offers to change this line into 4 other ways to accomplish the same result:
String.format()
StringBuilder.append()
java.text.MessageFormat.format()
Replace += with =
Why? What is so wrong with +=? Can anyone explain this please? Thanks.
In general case, the result is not the same. + operator allocates intermediate string, which requires additional memory.
String thing = "Something";
thing += " something else" + " and more."; // two allocations: to compute string inside expression ```" something else" + " and more."```` and to execute ```+=```
By using StringBuilder you don't allocate intermediate result, e.g. less memory is needed.
In your case with short lines and without loops no actual performance boost is expected. However with loops you receive O(N^2) complexity. Please check this answer with explained example.
I am assuming you are referring to this:
This is not actually a fix "problem" with your code, as indicated by the pencil icon. Fixes to problems with your code are identified with a lightbulb, such as not using the value of thing:
The pencil just means "here's a shortcut to change your code, so you don't have to change it manually". Changing a a += b to a = a + b usually isn't that much work, but other things, like changing a for-each loop to a regular for loop, is.
This could be useful if you suddenly remembered that you need the index of the array for something.

Parsing of math expression gives wrong tree

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

Java: Syntax error on token "-", Expression expected after this token [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Well hello guys, i'm starting the programmer life now, i'm really new into it, but i'm trying really, really hard and i'm making some easy programs to run on eclipse console, it's very simples 'cause i'm just getting started... well, everything went out ok, except for this one program, i can't make it work in no way... i'm gonna put it all here so if there's anything really, really wrong tell me, and i'm also going to expecific the problem that eclipse found... Here it is:
public class Pagamento {
public static void main(String[] args) {
int vvalor;
int vpagto;
int vtroco;
String voperador;
vvalor = 200;
vpagto = 250;
voperador = -;
if (vpagto > vvalor){
System.out.println ("Troco:" + vpagto - vvalor);
}if (vpagto = vvalor ){
System.out.println ("Troco:" + 0);
}if (vpagto < vvalor){
System.out.println ("Transação inconcluída!");
}
}
}
I had to define the " - " 'cause it asked to (when i did it, it said in the first System.out.println, that 'the operator - is undefined for the argument type(s) String, int and in the line' "}if (vpagto = vvalor ){" it appeared the error "can't convert from int to boolean), and when i did defined, it just gave this error on the line "voperador = -;":
Syntax error on token "-", Expression expected after this token. What does that mean ? Is everything so wrong ? What should i do to fix it ? Please help me, i try to search but i found nothing like this here, nothing that could solve my problem... thanks and please help !
it should be voperador = "-"; You have missed the double quotes. Strings are required to be enclosed within double qoutes
replace }if (vpagto = vvalor ){
with }if (vpagto ==vvalor ){
Also keep - with in ""(double qoutes) like voperador ="-";
voperador is a String, which can't be assigned to -. If you want the string to be "-", then use voperador = "-";
For your first error: This line isn't valid:
voperador = -;
String constants must go in quotes:
voperador = "-";
A - by itself is either a unary negation operator (e.g. -a) or a binary subtraction operator (e.g. a - b). The error you are seeing is the result of the compiler becoming very confused as to why a negation/subtraction operator was just hanging out between an equal sign and a semicolon.
For your second error: You have this:
if (vpagto = vvalor )
But you should have this:
if (vpagto == vvalor )
In Java, a single = means "assignment". Comparisons are done with the double ==. The reason you saw the error you saw is because Java evaluates the expression a = b to the value of a after the assignment (that's the rule), which in this case happens to be of type int (since vpagto is an int). At the same time, it expects the condition in an if statement to be a boolean (e.g. if (true) ...). The compiler was confused because it wanted a boolean but you gave it an int.
For your third error, you have this:
("Troco:" + vpagto - vvalor)
But what you really mean is this:
("Troco:" + (vpagto - vvalor))
Java evaluates expressions from left to right. As a convenience, it lets you add pretty much anything you want to a string, and the result is a string version of the values you've specified. However, this only works with +, there's no special definition of - for strings. Since it goes left to right, first "Troco:" + vpagto is evaluated, and that is a string. But then you try to subtract vvalor from a string, and the compiler complains. By adding parentheses, you tell it to perform the math on the integers first, before attempting to append the result to a string.
The errors you are making here are very basic. You should really go through the official Language Basics tutorial.

How is this construct called and which languages support it?

Java does not support this construct:
if ((int ext_pos = fname.lastIndexOf('.')) >= 0)
fname = fname.substring(0,ext_pos);
(I get syntax errors when compiling).
However, some other languages support things like that, e.g., in Perl I can write
if (defined (my $foo = $bar{$baz})) { ... do stuff with $bar ... }
# $bar does not exist here
Obviously, this is more of syntactic sugar than anything else, since one can re-write it in Java as
{
int ext_pos = fname.lastIndexOf('.');
if (ext_pos >= 0)
fname = fname.substring(0,ext_pos);
}
at the cost of 3 extra lines of code.
How is this construct called?
(Bonus questions: Which languages support it? Why don't Java & C++ support it?)
You have to move the declaration outside of the if-statement condition. Declarations are statements and can't be used as expressions
int ext_pos;
if ((ext_pos = fname.lastIndexOf('.')) >= 0)
fname = fname.substring(0,ext_pos);
In some languages as you point out (Perl), you can do this. This is because assignment in those languages can also be considered an expression and as such nested in other expressions.
(I'm not sure what this construct is called)
Java allows assignments inside expressions, but not variable declarations (thanks for the correction biziclop!). C++ has traditionally had the same restriction, but I found another stackoverflow post describing how declarations are allowed in conditions in the C++03 standard. The syntax is limited, but this is allowed (tested on GCC 4.2.1):
int x = 1;
if (int y = x)
cout << "y = " << y << endl;
Note that as biziclop pointed out, this has the nice property of restricting the scope of y to that within the conditional. If you try to use y outside the conditional you'll get an error:
int x = 1;
if (int y = x)
cout << "y = " << y << endl;
cout << y; // error: ‘y’ was not declared in this scope
I don't think there's actually a name for this—it's just allowing declarations in expressions. I don't think it's common enough to have its own specialized term.
As for language support. JavaScript sort of supports this in that it allows assignments in expressions, and that if you reference an undeclared variable in JavaScript it just assumes it's global.
if (x = 1) alert(x) // x is global, assigned 1
alert(x) // since x is global it's still in scope and has value 1
Basically, any language in which a declaration is an expression will allow you to do this. In most functional programming languages (e.g. Haskell, ML, Lisp), basically everything is an expression, so you can declare new variable bindings inside the condition (but they wouldn't be available in the body of the conditional). Here's an example in Clojure:
(println ; print the result of the conditional
(if (let [x 1] ; declare local binding x = 1
(== x 2)) ; check if x == 2
"is two" ; true branch result
"isn't two")) ; false branch result
Although Java doesn't like it when you to instantiate a variable inside the if statement, it will let you set one.
int ext_pos;
if ((ext_pos = fname.lastIndexOf('.')) >= 0) {
fname = fname.substring(0, ext_pos);
}
compiles correctly. I know that this is very similar to your solution, but I just wanted to point it out.
Similarly, Matthew Crumely answered a question about setting a variable inside the if conditional statement using another method here. In short, he notes that this can cause some code confusion for others that look at your code.. It can easily look like a noob mistake of using the wrong "=" or "==" even if it really is intended.
My real guess as to why they did this was to keep the code easily readable.
This is block notation. See Java specification section 14.2. Per The specification:
A block is executed by executing each of the local variable declaration statements and other statements in order from first to last (left to right). If all of these block statements complete normally, then the block completes normally. If any of these block statements complete abruptly for any reason, then the block completes abruptly for the same reason.
Section 14.3 shows an example with this syntax in it, you can also find this syntax throughout the specification.

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