I have the following method, but I want to use recursion; however, I get an error: "missing return statement".
static String buscar(NodoDeArbol raiz, String letra) {
if(raiz == null) {
aux="";
for (int i = 0; i < auxiliar.length()-1; i++) {
aux+=auxiliar.charAt(i);
}
return aux;
}
auxiliar = buscar(raiz.izquierdo, auxiliar+= "0");
auxiliar = buscar(raiz.derecho, auxiliar+= "1");
}
What should to do to fix this?
There are a couple of errors
First, you don't define aux (maybe is global?)
Second, you need to return a value when raiz != null
You are only returning a string when the case is null, but not returning anything when the case is not null.
You need to handle all cases. A return method (String) MUST return some sort of value.
You're if statement has the only return. You will need to add a return statement for the case that is not included in your if statement. Just judging by your current code, I'm guessing you meant to have return auxiliar; at the end of your method.
wrong is, that you return only when raiz is null, when you get parameter raiz, that is not null, method would never end - cause there is no return outside of if statement
Related
The below if statement should return the String "IllegalArgumentException", however it turns out to return an empty String instead.
I have tried to set a String variable output to store the expected String in the if statement.
public static String starString(int n){
if(n < 0){
String output = "";
return output = "IllegalArgumentException";
} else {
String stars = "";
for(int i = 0; i < Math.pow(2, n); i++){
stars += "*";
}
return stars;
}
}
I expect starString(-1) to return
exception:IllegalArgumentException
But the error message is an empty String.
The following statement is redundant:
return output = "IllegalArgumentException";
Instead you should just return the String or throw an exception.
return "IllegalArgumentException";
OR
throw new IllegalArgumentException("your message");
As for why it has is returning none is not understandable. Because I have run the code here and it works fine with giving the parameter as -1
Do not return a String "IllegalArgumentException", use throw new IllegalArgumentException("n should be non-negative") instead. Note that the exception message should always be meaningful and non-empty. You can set up the appropriate IDEA inspection which highlights creating exceptions without messages.
Don't use redundant else, this will save you one indentation level.
Don't use assignment operation result as a result. Although the language allows this, it is in most cases non-obvious to read and understand. You can setup IDEA inspection to avoid this as well.
I am trying to implement a search function. The function returns an object of type Prestamo if it finds a matching element. The function shouldn't return anything if nothing is found, but I get (of course) an error complaining about a missing return statement. How is this kind of problem solved? I guess Try-catch could be my friend for this, but I am struggling to understand that syntax.
This is my code:
public Prestamo buscarPrestamoPorUUID(UUID idPrestamo, ArrayList<Prestamo> listaBuscar) {
Iterator<Prestamo> it = listaBuscar.iterator();
Prestamo esteElemento;
while (it.hasNext()) {
esteElemento = it.next();
if (esteElemento.getActivo() && esteElemento.getIdPrestamo().equals(idPrestamo)) {
return esteElemento;
}
}
}
In Java, the control over a method must end in one of two ways:
A return statement, which returns an object of the type declared in the method signature OR null
A thrown exception (if the Exception does not extend RuntimeException, it must be declared in the method signature).
To resolve your compilation error, you need to do one of the two. If you want to do the former, it'd probably look something like this:
public Prestamo buscarPrestamoPorUUID(UUID idPrestamo, ArrayList<Prestamo> listaBuscar) {
Iterator<Prestamo> it = listaBuscar.iterator();
Prestamo esteElemento;
while (it.hasNext()) {
esteElemento = it.next();
if (esteElemento.getActivo() && esteElemento.getIdPrestamo().equals(idPrestamo)) {
return esteElemento;
}
}
return null;
}
Just be sure that the logic that invokes this method is prepared to handle null.
If you want to do the second, you'd do something like this:
public Prestamo buscarPrestamoPorUUID(UUID idPrestamo, ArrayList<Prestamo> listaBuscar) {
Iterator<Prestamo> it = listaBuscar.iterator();
Prestamo esteElemento;
while (it.hasNext()) {
esteElemento = it.next();
if (esteElemento.getActivo() && esteElemento.getIdPrestamo().equals(idPrestamo)) {
return esteElemento;
}
}
throw new RuntimeException("Didn't find an entity with the provided UUID!");
}
I personally prefer the former to the latter. It's a perfectly-valid use of null, and it makes the method easier to use than having to worry about uncaught exceptions. Regardless, note how that either implementation reaches a return or throw statement eventually. That's what your compiler checks for.
(P.S.: You can replace your while-loop with a for-each loop for code clarity.)
You could have it return null when no match is found. This would require the caller of the buscarPrestamoPorUUID() method to do a test for null and handle appropriately using a try/catch or some other way to handle it. ie:
Prestamo test = buscarPrestamoPorUUID(someID, someList);
if(test == null)
{ /* handle no match found */ }
else
{ /* handle result found */ }
Here is the code snippet:
private double input()throws IOException
{
StringTokenizer st=null;
BufferedReader b=new BufferedReader(new FileReader(csvfile));
String line=null;
int count=0;
while((line=b.readLine())!=null)
{
count+=1;
if(count==0)
{
return 0.0;
}
else
{
int sum=0;
String[] arr=new String[19];
st=new StringTokenizer(line,",");
int i=0;
while(st.hasMoreTokens())
{
arr[i]=st.nextToken();
i++;
}
for(int j=2;j<arr.length;j++)
{
if(j==13)
{
return Double.parseDouble(arr[j]);
}
}
System.out.println();
}
}
}
As you can see I've added a return statement for both cases of the if-else ladder. Eclipse is still asking me to add a return statement. Execution of the code raises an error for the same reason.(error : This method must return a result of type double)Why is this happening?
Background: The above method is to read a CSV file and return certain sections of the file as per the requirements of another method, which hasn't been shown here.
What happens if(j==13) returns false and never executes corresponding return? there is no return statement for this execution path right?
You need to have return statement for all executable paths.
There are several execution paths in your method that don't end in a return statement. All of them must do so. For example, the while loop might never be entered.
The easiest way to be absolutely sure is to add a return statement with a default value as the last statement.
There is no guarantee that else block return statement is going to execute,So you have to declare return statement outside.
In your case it is good practice to declare a variable outside and assigns it in if and else block and return it.
example:
double returnVariable = 0.0;
if(count==0)
{
returnVariable =0.0;
}
else
{
returnVariable = Double.parseDouble(arr[j]);
}
................
...........
return returnVariable ;
The problem is after this statement:
for (int j=2; j < arr.length; j++) {
if (j == 13) {
return Double.parseDouble(arr[j]);
}
}
If nothing is returned in that loop, Java is expecting you to return something afterwards. Java has no way to tell that the condition in the if is going to be true at some point, and in fact, it might never be true (what would happen if the array had less than 13 elements?).
The solution is to simply add an extra return at the end, with a returned value that makes it clear that the method exited under a non-expected circumstance - for example, if j was never equal to 13. Just add return -1.0; in the last line.
Your else part doesn't have a return statement directly. Instead it has it inside another if statement. Compiler can't determine if you will hot this check and returns.
In this section:
for(int j=2;j<arr.length;j++)
{
if(j==13)
{
return Double.parseDouble(arr[j]);
}
}
If you make it all the way through your loop, and don't find j = 13 (regardless if j is guaranteed to be there logically or not, programmatically that can't be determined by the compiler), then there is no applicable return statement.
You need to add a default case return statement AFTER your for loop.
As I was reading my AP java book I stumbled upon this section that made no sense to me:
...The getBalance method simply returns the current balance. A return statement obtains the value of a variable and exits the method immediately. The return value becomes the value of the method call expression. The syntax of a return statement is:
return expression;
or
return; // Exits the method without sending back a value
Why would you want to have a return statement and "exit the method without sending back a value" if you could just make it void?
***Note: Sorry if this may be too subjective. I just couldn't understand the point and the book doesn't explain it.
The return keyword doesn't need to be at the end. For example:
public static void print42(int[] numbers) {
for(int i=0; i<numbers.length; i++) {
if (numbers[i] == 42) {
System.out.println("has 42");
return;
}
}
System.out.println("no 42");
}
It can't just use a break, as that would print both strings.
This is kind of subjective. I'm old school, I believe in one entry and exit point for all methods/functions, but...
If you have a method with a void return type and if you had reached a point in your logic which would dictate that no further processing should take place, you could call return; to force the execution to return to the calling method at this point, foregoing any further execution of the method.
It would be the same as using something like return x; in the middle of a method body that had an expected return type (of whatever x is)
It's a little like using break to break out of a loop prematurely, except you're breaking out of the method before the execution gets to the end.
There are some situations where once you've verified something inside a void function, it makes sense to exit it immediately. For example:
public static void checkIfStringInList(List<String> searchList, String findString) {
for( String thisSearchString : searchList ) {
if( findString.equals(thisSearchString) )
return;
}
throw new Exception("String " + findString + " not found in list");
}
A method declared as void can exit with a return; this is just a shortcut for early termination. A method with a non-void return type must return a value of the right type, you can not have a method return "nothing" if it has a non-void return type.
If your method has a void return type, then the return statement is optional. You might want to use it anyway if, for instance, you wanted to stop execution in certain cases.
If the return type is not void, then using return; without an argument will give you a compile error.
In java if a method has a return type in its signature, you must return an object of that type or null before exiting the method.
for example
public A foo(boolean val){
A obj=null;
if (val){
obj=new A();
obj.setSomeAttribute();
}
return obj;
}
You can not compile source code if you just code "return;"
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.