I'm trying to call a boolean method in another class and Eclipse is reporting the above error on the second line in the following code:
CCR ccrFlags = new CCR();
if (ccrFlags.cBit() = set)
The method being called from the class called "CCR" is:
public boolean cBit() {
boolean set = false;
return set;
}
I imagine I'm probably going about this in an idiotic way and would be grateful for any advice. Thanks, Robert.
Comparison should use == (double-equal):
CCR ccrFlags = new CCR();
if (ccrFlags.cBit() == set)
in an if, the condition has to be always true or false.
your error is, that = only assigns the values, but it is not a logical operation which can be true or false.
So you have to use == in conditions.
Related
I'm curious is it possible to call a method that returns a boolean value in the condition part of a while loop?
As in:
while(someMethod()!= true){
//Do stuff
}
And the method simply returns a true or false. Is this possible or not and if so is there a correct syntax or a better way?
Edit: Thanks for the quick responses. As an extension to my question is it possible to call the method multiple times for different things but require them all to be the same before exiting the loop?
For example:
while(!(someMethod(input_a) == someMethod(input_b))){
//Do stuff
}
Where both of the returned values are the returned values are equal?
Hope this will help you
public boolean functionOne(int i){
// some operation
if(i == 1) return true;
else return false;
}
public void otherFunc(){
int i = 0;
if(functionOne(i)) { // e.g: if(functionOne(i) == true)
// your code
// 0!=1 so result is fort
}
if(!functionOne(i)){ // e.g: if(functionOne(i) == false)
// your code
// 0!=1 it is false, but ! before functionOne negate so ! of false is true
}
// **for your while**
while(functionOne(i)){ // while function returns true
// code
}
// **or**
while(!functionOne(i)){ // while function returns false
// code
}
}
Yes of course!
public static boolean someMethod(){
return false;
}
public static void main(String[] args){
while(!someMethod()){
//do something
System.out.println("Hi");
}
}
Like in this code, an infinite loop will be called if the method returns false, but if the method returns true, it will just come out of the while loop. :)
Less is best:
while (!someMethod()) {
// Do stuff
}
It's never a good idea to compare to a boolean result to a boolean literal. Prefer using the result in-line, using the logical unary not operator ! as required.
Answering the now-edited version of the question, less is still best:
while (someMethod(input_a) != someMethod(input_b))
You can find the specification of the while loop in JLS Sec 14.12:
The while statement executes an Expression and a Statement repeatedly until the value of the Expression is false.
WhileStatement:
while ( Expression ) Statement
WhileStatementNoShortIf:
while ( Expression ) StatementNoShortIf
The Expression must have type boolean or Boolean, or a compile-time error occurs.
So, you can use anything which is an Expression of type boolean (or Boolean).
And if you click through the productions in the language spec:
Expression, contains
AssignmentExpression, contains
ConditionalExpression, contains
ConditionalOrExpression, contains
ConditionalAndExpression, contains
InclusiveOrExpression, contains
ExclusiveOrExpression, contains
AndExpression, contains
EqualityExpression, contains
RelationalExpression, contains
ShiftExpression, contains
AdditiveExpression, contains
MultiplicativeExpression, contains
UnaryExpression, contains
UnaryExpressionNotPlusMinus, contains
PostfixExpression, contains
Primary, contains
PrimaryNoNewArray, contains
MethodInvocation
Phew! That's pretty deeply buried! (You can read this like an inheritance hierarchy, so every MethodInvocation is a PrimaryNoNewArray, and every PrimaryNoNewArray is a Primary etc).
So, transitively, every MethodInvocation is an Expression, hence it's fine to use it as the expression in a while loop.
Addressing your edit: yes, that's fine too. If you look at the detail of the EqualityExpression:
EqualityExpression:
RelationalExpression
EqualityExpression == RelationalExpression
EqualityExpression != RelationalExpression
As already described above, you can use an EqualityExpression as the Expression in a WhileStatement. And something of the form
RelationalExpression != RelationalExpression
is an EqualityExpression by the rule shown. Since all MethodInvocations are RelationalExpressions, you can use method invocations in the while statement as you've shown:
while(someMethod(input_a) != someMethod(input_b)) {
(a != b is an easier way of writing !(a == b)).
This is the way we have done loops over java iterators. For instance:
Iterator[String] iterator = util.Arrays.asList("One", "Two", "Three").iterator();
while(iterator.hasNext()) {
println(iterator.next());
}
We have also done something similar for the JDBC ResultSet interface.
I'm currently fixing a bug in someone else's Java code, but I cannot explain the bug. The code in question is the following if-statement:
if (locked && DEBUG_ENABLED
&& owner != null
&& (owner.equals(playerName) || subowner.equals(playerName))
&& handleCommand(playerName, message)) {
....
} else {
....
}
In which DEBUG_ENABLED is initialized as private static boolean DEBUG_ENABLED = false; and handleCommand functions like this:
public boolean handleCommand(String name, String msg) {
if(msg.equals("Command1")) {
....
} else if(msg.equals("Command2")) {
....
} ....
} else { // No matching command
return false;
}
return true;
}
What puzzles me is that even though DEBUG_ENABLED is set to false, the code still calls and executes the handleCommand function. I always thought this wasn't supposed to happen due to short circuiting.
The if-statement itself in total is still evaluated as false, since only the code inside the else-block in the first snippet is executed.
So, how come this if-statement is behaving like this? Is it failing to short-circuit, or do I misunderstand the principle, or is there something completely different wrong with this part of code? (Besides the missing null check for subowner that is, which is done outside of this part.)
It is not possible that the && operator fails to short-circuit. Were you using & perhaps? If not it means you have made some false assumptions that previous conditions before the last one were false.
I work with a Java project and Eclipse(Version 3.6.2) as IDE, in a enum comparison i get a strange behaviour, following an example of the weirdness :
Global Variable :
StatusType status = StatusType.SIGNATURE;
Code :
String trsStatus = "END";
if(trsStatus.equals("END") && (this.status.compareTo(StatusType.SIGNATURE) != 0)){
//Do something
}
This comparison succeeds and enter in the if block, Why ? In this case the second evaluation(this.status.compareTo(StatusType.SIGNATURE) != 0) of the if statements fail because the result is false ! Why java however enter in the block ???
If i evaluate the expression on the expression watcher of eclipse debugger the value of the statements are :
trsStatus.equals("END") ---> true
(this.status.compareTo(StatusType.SIGNATURE) != 0) ---> false
I've done another test, if i assign the result of the second expression in the if statements to a boolean variable :
boolean sign = (this.status.compareTo(StatusType.SIGNATURE) != 0);
i get this result :
(this.status.compareTo(StatusType.SIGNATURE) != 0) ---> false
sign ---> true
Why ?!?
How this can be possible ?
Could it be that StatusType overrides compareTo() in some weird way?
Are there any other threads that could be changing the value of the status field?
In any case, you should use equals() or even == rather than compareTo() here.
this.status.compareTo(StatusType.SIGNATURE) != 0 will return zero, because zero means they are equal. compareTo() returns either 1, -1, or 0, based on which value is considered greater.
The only sensible reason I could imagine is that
this.status != StatusType.SIGNATURE
Period. You probably set status to some other value unknowingly. Maybe with another thread. Who knows. What does status evaluate to, in your debugger?
In any case, there is certainly no such "bug" in Java. Unless you post some more code that proves it ;-)
You should use: this.status != StatusType.SIGNATURE.
public class Test {
public static void main(String[] args) {
TestEnum e = TestEnum.SIGNATURE;
System.out.println(e.compareTo(TestEnum.SIGNATURE));
String test = "test";
if (test.equals("test") && e.compareTo(TestEnum.SIGNATURE) != 0) {
System.out.println("I'm here");
}
}
}
I did the following test. It does not enter the if block and print "I'm here".
Can you post your snippet?
I am struggling with this error. I feel its really simple but cannot understand why am getting the error.
I keep getting a NullPointerException when I iterate through values in my linked list.
Code Snippet:
private void updateBuyBook(LimitOrder im) {
LimitOrder lm = null;
Iterator itr = buyBook.entrySet().iterator();
boolean modify = false;
while (itr.hasNext() && !modify) {
Map.Entry pairs = (Map.Entry) itr.next();
if ((((LinkedList<IMessage>) pairs.getValue()).size() > 0)) {
LinkedList<ILimitOrder> orders = (LinkedList<ILimitOrder>) pairs
.getValue();
ListIterator listIterator = orders.listIterator();
while (listIterator.hasNext() && !modify) {
LimitOrder order = (LimitOrder) listIterator.next();
if (order.getOrderID().equalsIgnoreCase(im.getOrderID())) { // error at this line
lm = order;
addToBuyMap(im);
modify = true;
break;
}
}
if (modify = true) {
orders.remove(lm);
break;
}
}
}
}
Error is at this line:
Exception in thread "main" java.lang.NullPointerException
order.getOrderID().equalsIgnoreCase(im.getOrderID()));
Please help. Is my assignment wrong in any way???
Please help!!!
Thanks
Changing your code a bit will make it longer, but much easier to find the error... instead of doing:
if (order.getOrderID().equalsIgnoreCase(im.getOrderID())) {
Change it to:
String orderID = order.getOrderID();
String imOrderID = im.getOrderID();
if(orderID.equals(imOrderID()) {
Then you will know if order or im is null. If neither of those is null then the things that could be null are orderID and imOrderID. It is now a simple matter of finding out which one of those is null.
If it is order or im then the program will crash on the order.getOrderID() or im.getOrderID() lines.
If, instead it is orderID or imOrderID that is null, then it will crash on if(orderID.equals(imOrderID()) {. You can then use System.out.println (or something better, like a debugger) do easily find out what is wrong.
If neither of those should be null then I suggest adding something like:
if(orderID == null) { throw new IllegalStateException("orderID cannot be null"); }
if(imOrderID == null) { throw new IllegalStateException("imOrderID cannot be null"); }
and then track down how it got set to null to begin with.
My guess would be that you're passing in the null, into im. I'll need to see more of the code to be sure.
You never check to see if im is null. I suspect it is.
One first look, where is im instantiated? You can also try to debug in your IDE so as to see whats going on?
Either im is null or order.getOrderID() is returning null.
Doesn't look like im is ever declared / assigned. So
im.getOrderID()
is probably where the null pointer exception is generated.
-- Dan
Edit:
Missed that im is passed in as an argument. So that leaves a few possibilities (in order of likelihood):
im is null (ie. user called function with null parameter)
order.getOrderID() is returning null
order is null (ie. the list has nulls in it)
Edit2:
Your line
if (modify = true)
Is fundamentally wrong and will always evaluate to true (single equal is for assignment, == is for comparison.)
When simply checking if a flag boolean is true or false, it is best to use:
boolean flag = true;
if(flag)
{
// True block
}
else
{
// False block
}
It will be good if you could add a debug point before that line and see which variable is null. looking at the code the answer is 1. order is null 2. order.getOrderID() is null or 3. im is null
I'm looking for a Google Collections method that returns the first result of a sequence of Suppliers that doesn't return null.
I was looking at using Iterables.find() but in my Predicate I would have to call my supplier to compare the result against null, and then have to call it again once the find method returned the supplier.
Given your comment to Calm Storm's answer (the desire not to call Supplier.get() twice), then what about:
private static final Function<Supplier<X>, X> SUPPLY = new Function<....>() {
public X apply(Supplier<X> in) {
// If you will never have a null Supplier, you can skip the test;
// otherwise, null Supplier will be treated same as one that returns null
// from get(), i.e. skipped
return (in == null) ? null : in.get();
}
}
then
Iterable<Supplier<X>> suppliers = ... wherever this comes from ...
Iterable<X> supplied = Iterables.transform(suppliers, SUPPLY);
X first = Iterables.find(supplied, Predicates.notNull());
note that the Iterable that comes out of Iterables.transform() is lazily-evaluated, therefore as Iterables.find() loops over it, you only evaluate as far as the first non-null-returning one, and that only once.
You asked for how to do this using Google Collections, but here's how you would do it without using Google Collections. Compare it to Cowan's answer (which is a good answer) -- which is easier to understand?
private static Thing findThing(List<Supplier<Thing>> thingSuppliers) {
for (Supplier<Thing> supplier : thingSuppliers) {
Thing thing = supplier.get();
if (thing != null) {
return thing;
}
}
// throw exception or return null
}
In place of the comment -- if this was the fault of the caller of your class, throw IllegalArgumentException or IllegalStateException as appropriate; if this shouldn't have ever happened, use AssertionError; if it's a normal occurrence your code that invokes this expects to have to check for, you might return null.
What is wrong with this?
List<Supplier> supplierList = //somehow get the list
Supplier s = Iterables.find(supplierList, new Predicate<Supplier>(){
boolean apply(Supplier supplier) {
return supplier.isSomeMethodCall() == null;
}
boolean equals(Object o) {
return false;
}
});
Are you trying to save some lines? The only optimisation I can think is to static import the find so you can get rid of "Iterables". Also the predicate is an anonymous inner class, if you need it in more than one place you can create a class and it would look as,
List<Supplier> supplierList = //somehow get the list
Supplier s = find(supplierList, new SupplierPredicateFinder());
Where SupplierPredicateFinder is another class.
UPDATE : In that case find is the wrong method. You actually need a custom function like this which can return two values. If you are using commons-collections then you can use a DefaultMapEntry or you can simply return an Object[2] or a Map.Entry.
public static DefaultMapEntry getSupplier(List<Supplier> list) {
for(Supplier s : list) {
Object heavyObject = s.invokeCostlyMethod();
if(heavyObject != null) {
return new DefaultMapEntry(s, heavyObject);
}
}
}
Replace the DefaultMapEntry with a List of size 2 or a hashmap of size 1 or an array of length 2 :)