I
I
Ivan Ivanov2020-01-03 16:40:04
Java
Ivan Ivanov, 2020-01-03 16:40:04

Why doesn't the function return a boolean variable?

Good afternoon, tell me please. I recently started learning Java and wrote a function that doesn't work, why? rewrote the function to javascript, everything works correctly.
5e0f43fa168c2030961610.png

public static boolean simpleNumber(int number){
        boolean result;
        for(int i = 1; i < number; i++){
            if(number % i == 0) {
                result = true;
            }
        }
        return result;
    }

The error is: Error:(118, 16) java: variable result might not have been initialized

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Panuhin, 2020-01-03
@IvanInvanov

The "variable result might not have been initialized" error means that when a variable is returned from a function, it may not have been defined yet. That is, if result = true does not happen , then the variable will not have a value (because at the beginning you simply created it - boolean result , but did not assign any value), the compiler swears at this. In your case, you just need to do: Then the variable will definitely have some value at the time of return.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question