KasiaKasia KasiaKasia - 7 months ago 25
Java Question

for-loop Java return value

I am very new to Java, sorry if the question is too simple. I am trying to evaluate whether an array is part of the fibonacci sequence. I do not know how to return "true" value when the whole "for" loop does not break. Any ideas? Thank you in advance! This is what I have for now:

public boolean checkFibb(ArrayList<Integer> array1) {
int i;
int fibb;

if (array1.size() < 3) {
System.out.println("Your array is too short!");
} else {
for (i = 0; i <= array1.size() - 2; i++) {
fibb = array1.get(i + 2) - (array1.get(i + 1) + array1.get(i));

if (fibb != 0) {
System.out.println("Elements are not part of the Fibonacci sequence.");
break;
} else {
System.out.println("Elements are part of the Fibonacci sequence.");
}
}
}

return true;
}

Answer

What you're doing in your code is you're breaking the current iteration of the loop when you detect that the elements aren't part of a fibonacci sequence. break only stops the current iteration of the loop that you are in. What you want to do is return false from the function at this point. When you detect that the array is indeed a fibonacci sequence you would want to return true at this point.

If you array is too short, it cannot be a fibonacci sequence thus you would return false at this point.

public boolean checkFibb(ArrayList<Integer> array1) {
int i;
int fibb;

if (array1.size() < 3) {
    System.out.println("Your array is too short!");
    return false;
} else {
    for (i = 0; i <= array1.size() - 2; i++) {
        fibb = array1.get(i + 2) - (array1.get(i + 1) + array1.get(i));

        if (fibb != 0) {
            System.out.println("Elements are not part of the Fibonacci sequence.");
            return false;
        } else {
            System.out.println("Elements are part of the Fibonacci sequence.");
            return true;
        }
    }
}

}