Peter Filip
Peter Filip

Reputation: 33

Issue translating script from python to java

I have a script, first written in python, then in java. With the given arguments, 100,50,9,3, the python script yields 1630. For some reason, the java version yields -22. Why is this? Is there a logic error in the java code?

Python:

def calcPopulation(E,P,R,Y):
    if E > 1000 or P > 100 or R > 50 or Y > 10:
        print("One or more values that you entered is too high")
        return None
    elif Y == 1:
        return E*2

    males = E
    females = E
    #^For first year
    for i in range(Y-1): #males
        males -= int((P*males)/100)

    for i in range(Y-1):
        females += int(-(P*females)/100)
        for i in range(int(females)):
##            femalebaby = (R/2)
##            malebaby = (R/2)
            females+= (R/2)
            males+= (R/2)
    return int(males+females)



def main():
    print(calcPopulation(100,50,9,3))
    #Result is 1630


if __name__=="__main__":
    main()

Java:

import java.util.*;

public class rabbit{

    public static int calcPopulation(int E,int P,int R,int Y){
        if (E>1000||P>100||R>50||Y>10){
            System.out.print("One or more of the values you entered is too high");
            return 0;
        }
        else if (Y==1){
            return E*2;
        }
        int males=0;
        int females=0;
        males += (int) E;
        females += (int) E;
        for(int i=0;i<(Y-1);i++){
            males -= (int) (P*males)/100;
        }
        for(int i=0;i<(Y-1);i++){
            females -= (P*females)/100;
            for(int x=0;x<females;x++){
                females += (R/2);
                males += (R/2);
            }
        }
        return (int) (males+females);
    }

    public static void main(String[] args){
        System.out.println(calcPopulation(100,50,9,3));
        //Result produces -22
    }


}

My best guess is that the for loops in the java code are operating differently than the python ones? I'm not sure, since i'm just a noob in java. Bottom line is I need the java script to produce the same result as the python script. Any help is appreciated.

Upvotes: 1

Views: 35

Answers (1)

Sweeper
Sweeper

Reputation: 271905

In python, when you divide an integer by an integer like 5 / 2, you get 2.5. But in Java, you get 2 because Java treats this kind of division as integer division. In python, you can use // to do integer division.

So lines such as this:

males -= int((P*males)/100)

will yield a different result in Java. To write this correctly in Java, you need to make one of the operands a double, like this:

males -= (int)((P*males)/100.0); // 100.0 is double, 100 is int.

Change all the lines where you have an integer dividing by an integer.

Upvotes: 2

Related Questions