Eclipse keeps telling me to add a return statement to the method, even though I did so.
public class PrefixCode {
public String isOne(String[] words) {
if(words.length==1) {
return "Yes";
}
ArrayList<Integer> indexPositions= new ArrayList<Integer>();
for(int i=0;i<words.length;i++) {
String firstWord=words[i];
java.util.List<String> listOfWordsToCheck = new ArrayList<String>(Arrays.asList(words));
listOfWordsToCheck.set(i,null);
for(int j=0;j<listOfWordsToCheck.size();j++) {
String secondWord= listOfWordsToCheck.get(j);
if(firstWord.startsWith(secondWord)==true) {
indexPositions.add(j);
}
else if(firstWord.startsWith(secondWord)==false);
}
}
if(indexPositions.size()==0) {
return "Yes";
}
else if(indexPositions.size()!=0) {
Collections.sort(indexPositions);
return "No,"+indexPositions.get(0)+"";
}
}
}
My return statements are outside of the for loops, so I don't understand what's wrong here.
There is no default return. The only returns you are making are if some conditions are true. What if the conditions are false?
Add a return after the last else block and you are all good to go.
The else block is redundant. What lies inside the else block should be be without else.
Since you have added if, else if, you need to else to that control flow to satisfy the compiler. Logically, size can be either zero or more than zero. So, you need to have if and else part only
if(indexPositions.size()==0){
return "Yes";
} else if(indexPositions.size()!=0){
Collections.sort(indexPositions);
return "No,"+indexPositions.get(0)+"";
} else {
// return what?
}
You can simplify this logic by,
if(indexPositions.size() == 0) {
return "Yes";
} else { //size more than zero
Collections.sort(indexPositions);
return "No,"+indexPositions.get(0) + "";
}
you should use else instead of
else if(indexPositions.size() != 0) {
Collections.sort(indexPositions);
return "No,"+indexPositions.get(0) + "";
}
The compiler doesn't know if the if conditions are going to succeed. So, you need to add a default return out of those if (even if your if conditions cover all possible cases!)
One of the best practice is to have only one return at the method end! Like this:
public String isOne(String[] words) {
String isOne = null;
if(words.length==1){
isOne = "Yes";
}
...
if(indexPositions.size()==0){
isOne = "Yes";
}
else if(indexPositions.size()!=0){
Collections.sort(indexPositions);
isOne = "No,"+indexPositions.get(0)+"";
}
return isOne;
}
Sometimes you may initialize the variable with a default value too, even if in this case is not needed :
String isOne = "No";
In also in your code there is an "error", the indexPositions.size may only be 0 or more, so you may want to use else instead of else if, and complete the graph. In this case eclipse won't tell you to add a return statement anymore, even if you use the return inside the condition block.
if(indexPositions.size()==0) {
return "Yes";
}
else {
Collections.sort(indexPositions);
return "No,"+indexPositions.get(0)+"";
}
I usually do this by declaring a boolean at the start of the function and set it to false. If for whatever reason the function says that variable is gonna be true. I set the declared variable to true instead of returning true. At the end of the function i return that declared variable.
It then has its default return and if the variable was set to true, it returns true.
Related
When I'm using while loop I need to use many if blocks which are exactly same So I planed to put it in a method and reuse it where I want! but I had a problem I want to return Continue or break in some area of my if blocks so can I return Break or continue?
while (true){
move(a);
move(b);
}
public *** move(Parameter parameter){
if (statement){
return continue;
}
else{
return break;
}
}
You can return a boolean:
while (true){
if(move(a))
{
break;
}
else
{
continue;
}
if(move(b))
{
break;
}
else
{
continue;
}
}
public boolean move(Parameter parameter){
if (statement){
return false;
}
else{
return true;
}
}
I'm going to set aside the fact if we implemented what you want literally then move(b); would be unreachable. Presumably when you say continue you mean execute the next statement; not return to the start of the loop?
But sadly you can't achieve this in Java. In Java, you can only return a value, not an "instruction". (In C and C++ you can contrive this using a macro, although that messes up your debugger.)
However, if you adapt move to return a boolean which is say true if you want to break and false otherwise, then at the call site you could write
while (true){
if(move(a)){
break;
} else if (move(b)){
break;
}
}
or ace it with
while (true){
if (move(a) || move(b)){
break;
}
}
where I'm exploiting the short-circuiting nature of the operator ||.
Finally, if you want to submit this code to an obfuscation contest then use the simply beautiful but still comprehensible
while (!(move(a) || move(b)));
and if you want to guarantee that you win said contest, then swap the return rule of move round and use the utterly indecent
while (move(a) && move(b));
Make it super simple with a returning boolean
public boolean move(Parameter parameter){
return statement;
}
while (true){
if(!move(a)) break;
if(!move(b)) break;
}
I'm learning Java at the moment and have a task where I should create a method that keeps asking the user for input until one of two keywords are entered. It should then, depending on that return an int.
public static int getCommand(){
String command = IOTools.readString("Enter Command!");
if (command.equals("exit")){
return 1;
} else if (command.equals("shift")){
return 0;
} else {
getCommand();
}
}
The problem I'm having is that eclipse tells me to either change the return type to void or add a return statement after the if block.
Is there something wrong with my recursive approach?
You are missing the return statement on your recursive call
public static int getCommand(){
String command = IOTools.readString("Enter Command!");
if (command.equals("exit")){
return 1;
} else if (command.equals("shift")){
return 0;
} else {
return getCommand(); // Added return here
}
}
you need to add a return type in last case
public static int getCommand(){
String command = IOTools.readString("Enter Command!");
if (command.equals("exit")){
return 1;
} else if (command.equals("shift")){
return 0;
} else {
return getCommand();
}
}
this function getCommand(); call is returning an int value but not in else case so if the control falls inside your else case then your recursive functions calls will be executed though there is no assurance that getCommand(); will return an int value due to else case so compiler detects that hence the error and according to this case where return type is not void , java says
Every execution path in a function must lead to a RETURN statement
Return statement is missing here
else {
getCommand();
}
All paths of your methode need to return something.
I'm new at programming with languages. Can anyone explain why do I get that "this method must return a result type of String" issue? And what is the simplest code to achive my goal ? Also what is wrong with my coding?
The goal I want to achive in this method is to return a string if it includes "o" in the first index it should return "o" in the output, as an addition if it includes "z" at the second index of the string, method should return it as "z", if it includes them both, I mean the input string begins with "oz..." method should return a string as "oz".
public String startOz(String str)
{
if (str.length() <= 1)
return str;
else
if(str.substring(0, 1).equals("o"))
if (str.substring(1, 2).equals("z"))
return "oz";
else
return "o";
Thank You.
You should re-arrange your code in a more readable manner :
public String startOz(String str)
{
if (str.length() <= 1) {
return str;
} else if (str.substring(0, 1).equals("o")) {
if (str.substring(1, 2).equals("z")) {
return "oz";
} else {
return "o";
}
} // no return value
}
This will let you see immeidately that if the first and second conditions are both false, you have no return value.
You can solve it by adding an else clause in the end that would return whatever you wish, or to simply have a return statement in the last line of your method.
Since you're new, I highly recommend you use braces. Bracing your code leads to a revalation:
if (str.length() <= 1) {
return str;
}
else {
if(str.substring(0, 1).equals("o")) {
if (str.substring(1, 2).equals("z")) {
return "oz";
}
else {
return "o";
}
}
// You need another return statement here OR
}
// You need one here.
As you can see now, there are instances where your function will return nothing, which is not allowed.
problem:
if(str.substring(0, 1).equals("o"))
You did not specify the return value if the string substring will be equals to "o"
solution:
add a return value when you hit that if statement so the compiler will know that method will return something
if(str.substring(0, 1).equals("o"))
return "value you want to return";
public String foo(String str)
{
if(str.substring(0,1).toLowerCase().equals("o"))
{
if(str.substring(1,2).toLowerCase().equals("z")
return "oz";
return "o";
}
else if(str.length() < 1) return str;
else return "o";
}
Be sure you are returning something if there is an if statement, otherwise it will skip over your line or cause you an error as you are having. This code checks the first character and then the second character. If it is neither it checks the length of the string, if its still none of those, it returns "o".
This is my method to find if a particular node is there in a binary tree.Here's my method and it works fine.
public boolean find(BinaryNode p,int x){
if(p==null){
return false ;
}
else{
if(x==p.element){
return true;
}
else if(x<p.element){
return find(p.left,x);
}
else {
return find(p.right,x);
}
}
}
My question is if I don't insert return keyword inside else if(x<p.element){ and else { I get an error as missing return statement.
Say I have a binary tree consisting of elements 5,4,6,60,25,10 .
So if i am searching for 10 there's a time that
if(x==p.element){
return true;
is satisfied because of recursive calls.Then there's a return statement to be found.
If i am searching for an element that's not in tree eventually I would reach the statement
if(p==null){
return false ;
},there we find a return statement.
Therefore even I don't have the return in else if and else clauses somehow there's a way that I finally reach a return statement right?So what's wrong with not having return keyword in else if and else clauses.
Why do I have to have it there?
Why can't I do it as
`public boolean find(BinaryNode p,int x){
if(p==null){
return false ;
}
else{
if(x==p.element){
return true;
}
else if(x<p.element){
find(p.left,x);
}
else {
find(p.right,x);
}
}
}`
The closest to the way you want your if-else if-else clause to behave is using the ? conditional expression:
public boolean find(BinaryNode p,int x)
{
if(p==null) {
return false ;
}
else {
return (x==p.element)?true:(x<p.element?find(p.left,x):find(p.right,x));
}
}
Other option is to store the value to be returned in a local variable and only return it at the end of your method:
public boolean find(BinaryNode p,int x)
{
boolean returnValue = false;
if(p!=null)
{
if(x==p.element){
returnValue = true;
}
else if(x<p.element){
returnValue = find(p.left,x);
}
else {
returnValue = find(p.right,x);
}
}
return returnValue;
}
And my favorite way, using short-circuit evaluation of logical expressions:
public boolean find(BinaryNode p,int x)
{
if(p==null) return false;
return x==p.element || (x<p.element && find(p.left,x)) || find(p.right,x);
}
Since Java's || and && operators won't evaluate their right part expression when the left part already determines their result. If x==p.element is true, then true will be returned without evaluation the rest of the line. If not, then (x<p.element && find(p.left,x)) will be evaluated following the same rule.
Note how find(p.left,x) won't be evaluated when x<p.element is false.
You need return statement because the find-function in the else if - else statement will return to the caller after its done, but the first-call function still have to return a value to the caller
Therefore even I don't have the return in else if and else clauses somehow there's a way that I finally reach a return statement right?
No compiler doesn't know about it. Compiler doesn't know what will be value of x and p at run-time.
Compiler simply checks for all the possibilities of the return statement and there must be exit point of the method.
You need to provide the logic to move either in right direction or left direction of the binary tree.
The last two else-if are not responsible to actually return the result of the find method its used just to move in the right direction of the tree. Ultimately final result of the the find method will come out by first two if-else clause.
I get an error in the code from this part of my code:
public boolean findCustomer(String inPersonalNumber){
// check if personal number already exist
for (int i=0; i<customerList.size();i++) {
if(customerList.get(i).getCustomerPersonalNumber().equals(inPersonalNumber)){
return true;
}
}
return true;
}
When I remove the first return true and instead to the last return true, it don't get the error in my eclipse code, but why can't I have the first place and would this be the same? Thanks!
EDIT: The error message from eclipse say: This method must return a result of type boolean. I'm confused because isn't that what I have done?!
Yes, a break must be in the code
Can I write the method in some other way?
EDIT NUMBER 2
Why isn't this code working?
public boolean findCustomer(String inPersonalNumber){
// check if personal number already exist
for (int i=0; i<customerList.size();i++) {
if(customerList.get(i).getCustomerPersonalNumber().equals(inPersonalNumber)){
return true;
}
else {
return false;
}
}
}
This method returns a boolean value so I don't understand why I get an error!? The code looks right to me?
Your edit #2 doesn't compile because there is a possibility that your code won't enter the for-loop. This will be the case if customerList.size() is 0. To fix this, you'll simply need to add a return statement after the for-loop as well:
// check if personal number already exist
for (int i=0; i<customerList.size();i++) {
if(customerList.get(i).getCustomerPersonalNumber().equals(inPersonalNumber)){
return true;
}
else {
return false;
}
}
return false;
Another point here is that this code doesn't logically make much sense: it will only return true or false based on the first item in your list. And this is probably not what you want. So take a closer look at several of the other answer here, many of which are good examples for how you can do this.
public boolean findCustomer(String inPersonalNumber){
boolean result = false;
// check if personal number already exist
for (int i=0; i<customerList.size();i++) {
if(customerList.get(i).getCustomerPersonalNumber().equals(inPersonalNumber)){
result = true;
break;
}
}
return result ;
}
When I remove the first return true and instead to the last return
true, it don't get the error in my eclipse code, but why can't I have
the first place and would this be the same?
If you remove the second return statement the code would be able to run and not return a value - this is not possible as you defined the method to have a return type of Boolean. So it must always return a value no matter what.
Just change the second return statement to false, should do what you want.
Looks like you have turned off the Build Automatically feature of eclipse. It maybe complaining about an error that used to be present when you still hadn't typed in your code fully! This can also happen if you have back-dated your system for some reason.
Also, shouldn't you be returning false if the condition doesn't satisfy?
public boolean findCustomer(String inPersonalNumber) {
// check if personal number already exist
for (int i = 0; i < customerList.size(); i++) {
if (customerList.get(i).getCustomerPersonalNumber().equals(inPersonalNumber)) {
return true;
}
}
return false;
}
First return will return only in case of all conditions satisfied, but this method should be returning boolean as per code. It would be expecting a return in failure case also.
Removing first return won't affect compilation as it has a return in second place which will work without any condtions.
Edit : Answer for your second question
This code has two return's, but what if your customerList is size 0, in that case also, method must return boolean. right? for that only, compiler is asking.
BTW, code doesn't have null checks.
Your final code could be this. Keeping multiple return statements in code in not a good practice.
public boolean findCustomer(String inPersonalNumber) {
boolean retVal = false;
if (!(inPersonalNumber == null || inPersonalNumber.trim().equals("")
|| customerList == null || customerList.size() == 0)) { // inputs are valid to run this check
// check if personal number already exist
for (int i = 0; i < customerList.size(); i++) {
if (inPersonalNumber.equals(customerList.get(i).getCustomerPersonalNumber()) { // to avoid NPE, kept inPersonalNumber in check
retVal = true;
break;
}
}
}
return retVal;
}
Because your for loop looses meaning if you're returning true anyway.
If you want to stop loop use break; instead of first return.