Whats wrong with my syntax on if statement using LineReader? - java

Can anyone see why I'm getting an error on this:
r = new LineNumberReader(new FileReader(txtFile));
for (int i = 1; i < txtFile.length(); i++){
if (r.getLineNumber() = (6*i)+1 || r.equals(1)) {
//code here
}
}
Error is:
Multiple markers at this line
- The left-hand side of an assignment must be a
variable
- The left-hand side of an assignment must be a
variable
- Syntax error on token ")", delete this token
But i can't see whats the issue is. Error is on the 3rd line
EDIT: I love you all, you've saved me once again! Guess I've spent to long with VB.net....

if (r.getLineNumber() = (6*i)+1 || r.equals(1))
should be
if (r.getLineNumber() == (6*i)+1 || r.equals(1))
Not sure what do you want to check with this r.equals(1) but you will most probably get false all the time, since you are compartir equallity between a LineNumberReader and an Integer.

In JAVA you compare two objects with two equals == , but in the if statement you put only one =.
So replace the = in the second line with the ==.
And please, write down this error somwhere you can remember it. Becouse every time you'll see it, then you'll know that it is caused by this same problem (mostly).

My wild guess would be:
if (r.getLineNumber() == (6*i)+1 || r.getLineNumber == 1)

should be == in stead of =
r.getLineNumber() == (6*i)

Related

How to put 2 condition in one statement actiolistener in java? [duplicate]

I'm a beginner in coding. I was recently working with to create a chatting programme where a user will chat with my computer. Here is a part of the code:
System.out.println("Hello, what's our name? My name is " + answer4);
String a = scanner1.nextLine();
System.out.println("Ok, Hello, " + a + ", how was your day, good or bad?");
String b = scanner2.nextLine();
**if (b.equals("good"))** { //1
System.out.println("Thank goodness");
} else **if (b.equals("it was good"))** { //2
System.out.println("Thank goodness");
} else **if (b.equals("bad"))** { //3
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
} else **if (b.equals("it was bad"))**{ //4
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
if(age<18){System.out.println("How was school?");}
else if (age>=18){System.out.println("How was work?");}
The conditions of the if statements are in Bold (surrounded with **). In case of first and the second condition I want my application to do same thing. Similarly third and fourth condition. I thought it was possible to somehow group them in if statement.
I tried with below code but it doesn't compile:
if (b.equals("good"), b.equals("it was good")) {
System.out.println("Thank goodness");
} else if (b.equals("bad"),(b.equals("it was bad"))) {
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
Can someone correct it for me?
You can use logical operators to combine your boolean expressions.
&& is a logical and (both conditions need to be true)
|| is a logical or (at least one condition needs to be true)
^ is a xor (exactly one condition needs to be true)
(== compares objects by identity)
For example:
if (firstCondition && (secondCondition || thirdCondition)) {
...
}
There are also bitwise operators:
& is a bitwise and
| is a bitwise or
^ is a xor
They are mainly used when operating with bits and bytes. However there is another difference, let's take again a look at this expression:
firstCondition && (secondCondition || thirdCondition)
If you use the logical operators and firstCondition evaluates to false then Java will not compute the second or third condition as the result of the whole logical expression is already known to be false. However if you use the bitwise operators then Java will not stop and continue computing everything:
firstCondition & (secondCondition | thirdCondition)
Here are some common symbols used in everyday language and their programming analogues:
"," usually refers to "and" in everyday language. Thus, this would translate to the AND operator, &&, in Java.
"/" usually refers to "or" in everyday language. Thus, this would translate to the OR operator, ||, in Java.
"XOR" is simply "x || y but both cannot be true at the same time". This translates to x ^ y in Java.
In your code, you probably meant to use "or" (you just used the incorrect "incorrect solution" :p), so you should use "||" in the second code block for it to become identical to the first code block.
Hope this helped :)
You're looking for the "OR" operator - which is normally represented by a double pipe: ||
if (b.equals("good") || b.equals("it was good")) {
System.out.println("Thank goodness");
} else if (b.equals("bad") || b.equals("it was bad")) {
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
This is probably more answer than you need at this point. But, as several others already point out, you need the OR operator "||". There are a couple of points that nobody else has mentioned:
1) If (b.equals("good") || b.equals("it was good")) <-- If "b" is null here, you'll get a null pointer exception (NPE). If you are genuinely looking at hard-coded values, like you are here, then you can reverse the comparison. E.g.
if ("good".equals(b) || "it was good".equals(b))
The advantage of doing it this way is that the logic is precisely the same, but you'll never get an NPE, and the logic will work just how you expect.
2) Java uses "short-circuit" testing. Which in lay-terms means that Java stops testing conditions once it's sure of the result, even if all the conditions have not yet been tested. E.g.:
if((b != null) && (b.equals("good") || b.equals("it was good")))
You will not get an NPE in the code above because of short-circuit nature. If "b" is null, Java can be assured that no matter what the results of the next conditions, the answer will always be false. So it doesn't bother performing those tests.
Again, that's probably more information than you're prepared to deal with at this stage, but at some point in the near future the NPE of your test will bite you. :)
You can have two conditions if you use the double bars(||). They mean "Or". That means only ONE of your conditions has to be true for the loop to execute.
Something like this:
if(condition || otherCondition || anotherCondition) {
//code here
If you want all of conditions to be true use &&. This means that ALL conditions must be true in order for the loop to execute. if any one of them is false the loop will not execute.
Something like this:
if(condition && otherCondition && anotherCondition) {
//code here
You can also group conditions, if you want certain pairs of them to be true. something like:
if(condition || (otherCondition && anotherCondition)) {
//code here
There is a simpler way.
if (b.contains("good")) {
...
}
else if (b.contains("bad")) {
...
}

Conditional operator for odd or even

I'm trying to write a program that that will find if there's an equal number of odds and even numbers in a given one, it's working great but it want to use conditional operator instead of these 4 rows (the // rows),
I'm getting this:
Syntax error on token "%", invalid AssignmentOperator
Can someone tell me why? What's wrong?
while(number!=0) {
//if(number%2==0)
//even++;
//else
//odd++;
number%2==0 ? even++ : odd++;
number/=10;
}
number%2==0 ? even++ : odd++;
This is not a statement. The result of a ternary must be assigned to something:
int x = number % 2 == 0 ? even++ : odd++;
However, this is stylistically quite awkward. I would use an if-else (i.e., what you originally had) over this pattern. Here you've created a temporary variable that you're never going to reuse, for the sole purpose of using a ternary.
It requires a variable at the left side at where you can place the value after the condition.
int tmp = (number%2 == 0)?even++:odd++;
number%2==0 ? even++ : odd++;
This statement is not assigning any value to number.As per my knowledge its always recommended for use if-else instead of ternary operator.
Because, in ternary operator the false/else part is compulsory to write, where in if-else else/false part is optional.
while(number!=0) {
//if(number%2==0)
//even++;
//else
//odd++;
int temp= number%2==0 ? even++ : odd++;
number/=10;
}
Now, temp variable is holding the value .

How to check for an Empty String

I am trying to assign a default value to variable if the variable holds an empty string. I used the following codes but they are not working out:
if (d.lat.trim().isEmpty())
latt = 9.0819990;
else {
latt = Double.valueOf(d.lat.trim()).doubleValue();
}
The above code results in an error:
cannot find symbol
symbol : method isEmpty()
location: class java.lang.String
then I used
if (" ".equals(d.lat.trim()))
latt = 9.0819990;
else {
latt = Double.valueOf(d.lat.trim()).doubleValue();
}
The code above jumps the if section and tries to convert the empty String into double thereby throwing error about empty string.
SO, what am I doing wrong?
The empty string is "", not " " (note that there is no space between the quotes).
NPE is correct.
But may I recommend Apache StringUtils .
http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html#isBlank(java.lang.String)
Checks if a String is whitespace, empty ("") or null.
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
The first block looks ok to me, but you are probably compiling with Java5, which does not have the String.isEmpty() method yet.
What if you use String.length() == 0 instead of String.isEmpty() ?
Apache StringUtils is a very good way to solve the problems for the validation you're implementing. Nevertheless, it seems very strange the error that you can't use the .isEmpty method, what version of the JDK are you using? Try to change the version of your JDK in the classpath with a latest version (JDK 7) or at least with the JDK 6.
Also remember that empty String is represented by "", just the quotes without any blank. It seems the way you're validating is ok. You can try with something like this.
if (d.lat.trim().isEmpty() || d.lat.length == 0)
latt = 9.0819990;
else {
latt = Double.valueOf(d.lat.trim()).doubleValue();
// or as mentioned before: latt = Double.parseDouble(d.lat.trim());
}

"Invalid assignment" error from == operator

I was trying to write a simple method:
boolean validate(MyObject o)
{
// propertyA && propertyB are not primitive types.
return o.getPropertyA() == null && o.getPropertyB() == null;
}
And got a strange error on the == null part:
Syntax error on token ==. Invalid
assignment operator.
Maybe my Java is rusty after a season in PLSQL. So I tried a simpler example:
Integer i = 4;
i == null;
// compile error: Syntax error on token ==. Invalid assignment operator.
Integer i2 = 4;
if (i == null); //No problem
How can this be?
I'm using jdk160_05.
To clarify: I'm not trying to assign anything, just do an && operation between two boolean values. I don't want to do this:
if (o.propertyA() == null && o.propertyB() == null) { return true; }
else { return false; }
== is not an assignment operator, it's a boolean equality operator, see:
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.21.2
If you want to set i to null use the simple assignment operator =:
i = null;
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.26.1
If you want to check that i is null then you need to use the == operator
if (i == null)
I don't think you are confusing assignment and equality comparison. I think your compiler is just giving you a confusing error message. This program:
Integer i = 4;
i ==null;
should give an error something like this:
Program.java:8: not a statement
i ==null;
Your first program should compile correctly. Perhaps there is some invisible unicode character in the text that is confusing the compiler. Try deleting the entire function and typing it in again.
I think I see your problem. I'm sorry the other answers don't address it.
So, Java has this idea that is shared by some other languages that just because something is a valid expression doesn't mean that that thing, by itself, is a valid statement.
For example, this code will complain similarly:
Integer i = 4;
i+3; // this line gives a compilation error
And yet obviously I can use i+3 (go unboxing!) elsewhere to mean "7":
System.out.println(i+3); // this is fine
It gets a bit confusing because unlike some languages that have this expression/statement distinction, java allows you to use any method call - whether it returns a value or not - as a statement. However, most java operators do not - by themselves - form a valid statement.
Likewise, this fails to compile:
Integer i = 4;
i; // this line gives a compilation error
For the full gory details, see http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#32588
In PL/SQL, assigning a value to a variable is done with the := operator. Comparing two values is done with =.
In Java, assigning a value to a variable is done with the = operator. Comparing two values is done with ==, or a .equals() method in some cases.
You can do things like this:
x = i==null;
This will test if i is null and if so, the value true will be assigned to x (assuming that x is a boolean).

Using a string containing variables in JOptionPane

I am trying to build a string using "if" statements, and then using the built string to show in a JOptionPane.
//If the value is zero, don't show the line item
if (intLays > 0)
strBuiltOrder = "intSnickers + \"Snickers\" + \"\\n\"";
In the end there would be one line item for each variable that had a value greater than zero. However, the problem is, when I use it in JOptionPane, it outputs the literal.
intSnickers + \"Snickers\" + \"\\n\"
Is there anyway I can build a string to insert into JOptionPane, or is there another way to withhold variables from the JOptionPane if their value is zero?
Is there a reason why you escape quotes and backslashes? The following probably does what you expect:
if (intLays > 0) {
strBuiltOrder = intSnickers + "Snickers\n";
}
If you want to build a more complex string you can look into StringBuilder or StringBuffer objects.
Along my own presumption, maybe you were looking for this:
//If the value is zero, don't show the line item
if (intLays > 0)
strBuiltOrder = intSnickers + "\"Snickers\"" + "\"\\n\"";
I hope this helps, or at least points you in the right direction, when I understand more about the expected output I can try to help you out further.
Instead of using a String, try using a StringBuilder then you won't have problems with the syntax of that statement. So your code might be something like:
StringBuilder sb = new StringBuilder(...);
...
if (intLays > 0)
sb.append(intSnickers).append("Snickers\n");
Strings are immutable, so it better to use something like the StringBuilder or StringBuffer.
The solution was:
if (intSnickers > 0)
BuiltOrder.append( intSnickers + "Snickers" + "\n");
This is meant to concatenate a string and insert it into a JOptionPane. I am still sort of confused about why it works this way, instead of the way I have it, but, oh well...

Categories