Ale K.
Ale K.

Reputation: 316

2 returns firing in the same function?

Well been working for hours today so i might be missing something silly, but, at this point I'm kinda blind with this and looking for an explanation for this behaviour

i made an example of the problem I'm having and the solution i found is not quite a solution.

The Problem: to the following function I pass 1 as shotCount and 9 as Countdown the result when i debug, i see the first if run, and run the return 2, but then also the else decides to run to and finally return -1

    public int getNextShot(int shotCount, int Countdown)
    {
        if ((shotCount == 1) && (Countdown != 10)) return 2;
        else if (shotCount == 0) return 1;
        else return -1;
    }

BUT if i do this (same parameters) it works:

   public int getNextShot(int shotCount, int Countdown)
    {
        int res = -2;
        if ((shotCount == 1) && (Countdown != 10))  res = 2;
        else if (shotCount == 0) res = 1;
        else res = -1;
        return res;
    }

Am I missing something here?

Thanks :)

Upvotes: 0

Views: 103

Answers (2)

zacheusz
zacheusz

Reputation: 8842

This code is OK. When I run this:

public static int getNextShot1(int shotCount, int Countdown) {
    if ((shotCount == 1) && (Countdown != 10)) {
        return 2;
    } else if (shotCount == 0) {
        return 1;
    } else {
        return -1;
    }
}
public static int getNextShot2(int shotCount, int Countdown) {
    int res = -2;
    if ((shotCount == 1) && !(Countdown == 10)) {
        res = 2;
    } else if (shotCount == 0) {
        res = 1;
    } else {
        res = -1;
    }
    return res;
}
public static void main(String[] args) throws KeyStoreException, ParseException {
    System.out.println(getNextShot1(1, 9));
    System.out.println(getNextShot2(1, 9));

}

I get

2
2 

on console :) Second function could look like this (final keyword):

public static int getNextShot2(int shotCount, int Countdown) {
    final int res;
    if ((shotCount == 1) && !(Countdown == 10)) {
        res = 2;
    } else if (shotCount == 0) {
        res = 1;
    } else {
        res = -1;
    }
    return res;
}

Upvotes: 0

Kal
Kal

Reputation: 24910

I think you are mistaken.

Sometimes the debugger in Eclipse acts like its jumping to the last line of the method call but then does return the correct value.

For example, I just copied and pasted your code and it ran fine for me. The below code prints 2.

public class AA {

        public static void main(String[] args) {

                System.out.println(getNextShot(1, 9));

        }

        public static int getNextShot(int shotCount, int Countdown)
    {
        if ((shotCount == 1) && (Countdown != 10)) return 2;
        else if (shotCount == 0) return 1;
        else return -1;
    }
}

Upvotes: 4

Related Questions