Java boolean "Unexpected return value" - java

I'm new to Java and I can't understand why the IDE says that "Unexpected return value" inside the forEach where I declared that the boolean is true or false by an If statement.
My goal is to check that there is an object inside the "States" HashMap which already uses the name that I want to set to a new state. (The HashMap's key is a String which is called IdentifierOfState and the value is my State object which contains variables like its name.) Thank you for your help in advance!
public boolean isStateNameClaimed(String NameOfState)
{
States.forEach((IdentifierOfState, ValueOfState) ->
{
if (ValueOfState.getNameOfState().equalsIgnoreCase(NameOfState)) {return true;}
else {return false;}
});
return false;
}

The problem is that you are attempting to return the results in the wrong place. The {return true;} and {return true;} are in a lambda, so they are attempting to return a result for the lambda. But the inferred type signature for that lambda doesn't allow any values to be returned.
If your intention is that those return statements should be returning a result from isStateNameClaimed, then the better solution is to just use a for loop to iterate the elements of States.
It doesn't help things that your Java code contains a number of egregious Java style violations. You should NOT start the name of a variable with an upper-case letter. It will confuse ... and then annoy ... other people reading your code.
You may say: "Nah, I don't need to follow the rules, 'cos nobody else will be reading my code". But you are asking >>us<< to read your code.
I'm new to Java ...
... so NOW is the time to learn to do it correctly. Java style matters to people reading your code.
This is how I would write it in classic Java:
public boolean isStateNameClaimed(String name) {
for (State v: states.values()) {
if (v.getNameOfState().equalsIgnoreCase(name)) {
return true;
} else {
return false;
}
}
return false;
}
Or using streams:
public boolean isStateNameClaimed(String name) {
return states.values().stream().anyMatch(
(v) -> v.getNameOfState().equalsIgnoreCase(name));
}
Actually ... I just noticed that those two solutions are not equivalent. And based on your description of what you are trying to do, it probably means that the first one and your original attempt are algorithmically incorrect.

forEach will invoke a given callable function for every element. We can't have return value to that function.
Try using "filter" or assign result to local variable.
Return from lambda forEach() in java

Related

Calling a method in the while loop condition

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.

Trying to come up with solution using recursion

I know there are multiple ways to find out if a word is palindromic, like using the reverse function of StringBuilder or even the reverse function of Collections, but in an attempt to learn recursion, I wrote it this way. I even had it working iteratively.
I kind of added return true in my embedded else statement, but I'm really not sure what to do, because when I run this in debug mode, it returns false, then invokes checkPalindrome again, which I don't understand why, because it should return and terminate, no? I would really appreciate an explanation of what I'm doing wrong and how to get it working this way.
public static boolean checkPalindrome(Deque deq) {
if(deq.pollFirst() != deq.pollLast()) {
return false;
} else {
if(deq.size() == 1 || deq.size() == 0) {
return true;
} else {
checkPalindrome(deq);
return true // TODO ?? figure out What to put here ??
}
}
}
It's that you are not returning anything when you call yourself. The inner else statement should read this:
else {
return checkPalindrome(deq);
}
You have a followup question in the comments below that leads me to want to explain how recursive methods work, but in essence, they all follow the following pseudo-code:
public boolean someMethod(T[] someArrayOrList) {
// return true -OR-
// return false -OR-
// call yourself and return whatever that call returns
}
No matter what, when you call the method it will return SOMETHING... Either it will return something itself, or it will return whatever some other call of itself will return. In a way it is AND'ing all the responses, but in reality TRUE is only generated once.

Returning multplie values of the same type in Java

I need to return 3 values of an object I created in a method I created. I can put this code in my while loop and it executes how I want it to execute. But I want to keep it in a method just to modularize my program and keep the code organized. Im using the ACM library which is for academia purposes.
public GObject asteroidLocation(){
if(asteroid1.getX() >= AW)
{
asteroid1.setLocation(0,150);
}
else if(asteroid2.getX() >= AW)
{
asteroid2.setLocation(0,80);
}
else if(asteroid3.getX() >= AW)
{
asteroid3.setLocation(0,20);
}
return asteroid1, asteroid2, asteroid3;
}
What you need is a java.util.List
For your use-case you could just do this:
return Arrays.asList(asteroid1, asteroid2, asteroid3);
Your return type then would be List<GObject>
So return a List<Asteroid> or whatever type asteroid is. Even better is have an object you create that has a List<Asteroid>, has a getAsteroids() method and return that.
Have you tried Tuples (https://en.m.wikipedia.org/wiki/Tuple) and Triples?
Java don't provide any but it's pretty straightforward to implement. I can give you an example if needed.
Instead of returning the value outside the if condition return it from within. For example,
if(asteroid1.getX >= AW)
{
asteroid1.setLocation(0,150);
return asteroid1;
}
This way you could simplify the code and pass only one return value to the class
A direct answer to you question "multplie values of the same type in Java" would be:
An array: GObject[]
Any generic collection, e.g. List<GObject>

Return keywords for a boolean statement

I am writing an incredibly primitive blackjack game for a high school programming class and I am playing with writing a boolean as such:
public boolean DealerTracker()
{
if(a==11 || a==12|| a==13)
{
a = 10;
}
dealerHandValue = a + dealerHandValue;
if(dealerHandValue>21)
{
DealerHand.setText("The House went bust!! Everybody wins!!");
return true;
}
else if(dealerHandValue<21)
{
return null;
}
else if(dealerHandValue==21)
{
return false;
}
}
I keep getting an error saying that return null (I couldn't manage to get the fancy blockquote to work) is invalid. However, for this boolean to work I really need three return statements. So my question is this: Is there a way to make null work, or is there something I can put in its place that is still usuable, or am I just being stupid here.
Please note that I do not really need this boolean, so if you think that there is no solution, just advise deletion of the boolean.
Primitives booleans can only return values true or false. You need to return the Object wrapper type for boolean
public Boolean dealerTracker() {
...
boolean primitives cannot be null. You basically have two options I can see:
Have your function return a Boolean (note the capital 'B'). Boolean is an object, rather than a primitive, and so can be null.
A better solution would be to define an enum. That helps you preserve the semantic meaning of the return value, which will make your code more readable and easier to maintain.
If you don't really need the boolean, make the return type void and remove all return statements. If you do need boolean AND null, change the return type to Boolean, which will return a boolean wrapped in an object that can actually be null. The method that calls this method can then receive a true, false, or null, since null actually represents something too (although I'm not sure in this case it represents anything meaningful).

What does this boolean setter mean?

I am assigned some maintenance task for a Java program and found this:
public void setActiveCode(boolean isActiveCode) {
this.isActiveCode = isActiveCode & Boolean.TRUE;
}
The type of this.isActiveCode is a boolean, The same concept is repeated for every boolean setters in the class. I can't figure out why it is done this way and I can't ask the original developer.
Would there be any valid reason for doing this?
Would there be any valid reason for doing this?
No. This is just more verbose code with zero gain in clarity (and arguably a loss in clarity since here you are wondering what it's all about).
It reminds me of
public boolean isTrue(boolean b) {
if(b == true) {
return true;
}
else {
return false;
}
}
which unfortunately you will see in the wild from time to time. It's just so sad.
Its weird. Booleans can be used with logical &, but this is useless because a & true = a. Seems to be a developer specific OCD.

Categories

Resources