Input validation (do while loop) - java

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)

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: 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 to test if string is equal to "x" || "X"?

String c = JOptionPane.showInputDialog(null,"Pick a conversion to do:\nGrade");
if (c.equals("grade")||("Grade"))
I want it to start if the user enters grade or Grade not just grade, but when I use this I get a error. How would I fix that
The actual problem: You're using || improperly. It expects, on both sides, something of type boolean to be present.
From the JLS:
Each operand of the conditional-or operator must be of type boolean or Boolean, or a compile-time error occurs.
Since "Grade" isn't a boolean (but c.equals("grade") is), this becomes a compile-time error.
While you could fix it by correcting the boolean on the right hand side...
if(c.equals("grade") || c.equals("Grade"))
...why not do it in a more straightforward way?
if(c.equalsIgnoreCase("grade"))
This particular equals on String was likely engineered for this use case (or other use cases, as "GrAde" would fail your check too). It will perform a length check on your strings first, then a case insensitive comparison on each element.
You cannot put an || statement in the middle of a method call like that.
if (c.equals("grade")||c.equals("Grade")){
//do stuff
}
There are other ways to accomplish your task, IE using other methods, but your problem is coming form a misuse of the || operator.
You can try:
if (c.toLowerCase().equals("grade")) { }

The Swedish Chef Translator

So the context is, I have a CS project where input is taken in either word or sentence form, and then it is translated to what The Swedish Chef from The Muppets would say. I decided to take the input as one line of string, and send that line into a parser, which in turn would build an array out of translations of the input's letters. The conditions for what gets changed are defined within. the current error I am getting: (while using "INPUT" as input)
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 1
at java.util.ArrayList.rangeCheckForAdd(Unknown Source)
at java.util.ArrayList.add(Unknown Source)
at SwedishTranslator.parseString(SwedishTranslator.java:62)
at SwedishTranslator.main(SwedishTranslator.java:12)
Currently it is supposed to just print the array, I wanted to worry about formatting after the fact.
The code:
Sorry for the walls of text but I can't find where the issue is exactly and I figured I would give it a shot here. Thanks in advance.
ind<=in.length() goes one step too far.
Use ind < in.length() or ind <= in.length() - 1
The error arrises on line 62 which I assume is in your big if else section.
Within there you have several ind++ calls. This increments the pointer you use in the loop. So if your code must go through several of these statements it will go beyond the array index.
Additionally you have an issue in the for loop as joval mentioned
Edit
The ++ unary operator increments the variable (-- decrements). Placing the ++ after the variable name (x++) will increment before evaluation, where ++x will increment after evaluation.
This is a common test question for CS students so I suggest you do some more research and practice regarding the operator.
You're making a couple of really understandable beginner mistakes here. Instead of explicitly fixing your code, I'll tell you about a couple of things that, if considered while reviewing and editing your code, will also fix your problem.
The documentation for String.charAt http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#charAt(int) throws an error when you attempt to access out-of-bounds items in the String. Make sure that you check that you're not attempting to look beyond the length of the String before you go calling charAt all willy-nilly! If you're currently "considering" the 'T' in "INPUT" and you go trying to look at the next two characters, Java will complain.
Second, and this is more of a general thing (though it does need to be fixed in your code above); the '++' operator doesn't do what you appear to think it actually does. When you do this: in.charAt(ind++)=='H', you may think you're just checking on the value at the next index, but you're actually advancing the index at the same time! The '++' operator is very handy, but it has a side affect that trips up a lot of beginners: it assigns itself + 1 to itself! That means that if you're on the 'I' in "INPUT" and somewhere within your loop you call ind++ once, you'll be on 'P' at the next iteration of your loop! When you see '++' remember that you're changing the value of the variable.
Good luck!

Ternary operator not working in Android

I have a simple question that boggles me. I am trying to use the ternary operator in java. I am new to Android and java. This code gives me the error:
amt < 0 ? lendBtn.setChecked(true) : lendBtn.setChecked(false);
"Syntax error on token "<", invalid AssignmentOperator"
So, I replace it with an if statement and it totally works:
if (amt < 0) { ... }
It's not a big deal but does anyone know why?
This has nothing to do with Android. You can't use a conditional expression as a statement on its own... and the second and third operands can't be void expressions either.
You should use:
lendBtn.setChecked(amt < 0);
... which is simpler to start with.

Categories

Resources