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

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.

Related

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: Unexpected Type Error [duplicate]

This question already has answers here:
Replace a character at a specific index in a string?
(9 answers)
Closed 8 years ago.
Can someone help me understand why I'm getting an "Unexpected Type Error"?
if(s.charAt(i-1) == ' '){
String sub = s.substring(i, s.indexOf(' ')+1);
for(int j = 0; j < sub.length()/2; j++){
char temp;
temp = sub.charAt(j);
sub.charAt(j) = sub.charAt(sub.length()-1-j);
sub.charAt(sub.length()-1-j) = temp;
sub = sub+" ";
complete = complete+sub;
}
}
I'm getting the error on lines 6 and 7. I can't figure out why and I'd appreciate the help!
charAt() returns the character. It is not a left side operand aka you cannot assign a value to it.
Strings are immutable, which means you cannot change them (this seems to be your intention).
Instead: create a new String and add to that.
If this confused you, I try to elaborate a little: the assignment operator takes whatever is on the right and tries to shove it into whatever is on the left of it.
The problem here is that some things do not like it when you try to shove other things into them. You cannot put everything on the left that you want. Well, you can try:
"everything" = 5;
but this does not work, neither does this:
"everything" = 42;
Set aside what that last snippet failing implies to the universe and everything, your problem at hand is that charAt() is also one of those things that do not like it on the left side of the assignment operator.
I'm afraid there's no way to turn charAt() into one of those things that like it on the left side. A week after stranding on a deserted island without any plants but only solar powered refrigerators filled with steaks, this probably works:
vegetarian = meat;
Even though the vegetarian doesn't like it there, he'd accept his situation being on the left side of the = operator. He eats some steaks.
This does not hold true for what you are trying, though. There's no such deserted island for charAt().
In these lines you're trying to set the value of functions' return. This is illegal
sub.charAt(j) = sub.charAt(sub.length()-1-j);
sub.charAt(sub.length()-1-j) = temp;
as far as I see you're trying to change the characters of a String, but Strings are imutable objects. So you'll need to use a StringBuffer to set the values.

Invalid Assignment Operator 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

Input validation (do while loop)

I need to make sure the value entered for the prompt is in between 100,000 and 900,000, and this isn't working, any ideas? (I'm only a beginner btw)
double advertCost;
do {
System.out.println("Please enter the advertising cost: ");
advertCost = input.nextDouble();
} while (advertCost =< 100000 || advertCost => 900000);
The error I get:
Syntax error on token "<", delete this token
The operator || is undefined for the argument type(s) int, boolean
Syntax error on token "=", delete this token
Your issue is in your syntax:
while (advertCost =< 100000 || advertCost => 900000);
In Java, the "less than or equal to" operator is as you say it. LESS THAN or EQUAL to. You've got EQUAL TO or LESS THAN. Same goes for your greater than as well. It should look like this:
while (advertCost >= 100000 || advertCost <= 900000);
Also, you had your operators the wrong way around. You want advertCost to be greater than 100000 and less than 900000 but your operators imply less than 100,000 and greater than 900,0000.
Just an aside about your error
Often these sorts of issues can be understood by the error message. I know that they can seem cryptic but if you learn to decipher them, you really will have little need for us in terms of syntax errors.
Syntax error on token "<", delete this token The operator || is undefined for the argument type(s) int, boolean Syntax error on token "=", delete this token
Let's cut it up into it's parts:
The first part
Message:Syntax error on token "<", delete this token
Well, the JRE has just parsed your code, and it is going through each token. This is the first token it has reached that is invalid, so this message is generated. However, if you delete this, you'll still have an invalid if statement, so let's read on.
The second part.
Message:The operator || is undefined for the argument type(s) int, boolean
Well, no detectable operator has been found, so the JRE has to assume there isn't one there. When it has parsed part of the IF statement it's found:
if(a number || something else).
At this point it knows that the || operator only works on two boolean values, so it throws another error. It does this because it already knows the code will fail; it doesn't need to check the other side.
The last part
Message:Syntax error on token "=", delete this token
So the JRE has continued parsing, and it's also found your "=>". As before, it's noted the invalid character and recommended you remove it. If you do remove the "=", then you actually have valid syntax for this part of the If statement.
Summary
Next time you're faced with this type of error, simply try to break down the message. It tells you what characters are wrong, < and =. It even tells you what to try with them. Obviously it can only guess, so it's down to you to work out what you want and how to make the Runtime Environment understand that!
The comparison operators are <= and >=, not =< and =>.
(advertCost <= 100000 || advertCost >= 900000)

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