[Solved] Why am I “missing return statement” in one case, but not the other?

[ad_1]

As already mentioned by the other answers, the reason why this is happening is because you declare your function as returning a boolean but it is possible for you to execute your function without actually hitting a return statement. For example imagine if Just to be a bit more explicit here is your code and where extra returns are needed:

    public static boolean checkL2(File file) throws IOException
    {
        Stack l2Stack = new Stack();
        boolean bStart = false;
        char w;

        Scanner sc = new Scanner(file).useDelimiter("\\s*");

        while(sc.hasNext()) //Load input from file onto stack
        {
            w = sc.next().charAt(0);

            if (w == 'A')
            {
                if (bStart == true)
                {
                    return false;
                }
                else
                {
                    l2Stack.push('A');
                }
            }
            if (w == 'B')
            {
                bStart = true;
                if (l2Stack.isEmpty() == true)
                {
                    return false;
                }
                else
                {
                    l2Stack.pop();
                }
            }
        }
        sc.close();
        if (l2Stack.isEmpty() == true)
        {
            return true;
        }
//Added return 
    return false;
    }

This added return is necessary because imagine what would happen if when your while loop finishes, l2Stack.isEmpty() == false, in this case you would reach the end of a “non-void” function without returning anything which Java does not allow. There is no default return action, you must explicitly declare what you want to return in every case.

[ad_2]

solved Why am I “missing return statement” in one case, but not the other?