Robin Bakker
Robin Bakker

Reputation: 35

Comparing two ints and using the diffrence for a calculation

I have set a personal score to a player in the game that I am making. I want to update this score if the player wins, but the amount it raises or drops is depending on the difference in personal score.

public int editScore(int personalScore){

if(endOfGame().getResult().equals("win")){

now I want to get both players their personal score and compare them to determine how much points will be assigned:

        if(this.getPersonalScore.compareTo(partner.getPersonalScore))

How will I make this work? I will need a return of the difference between the two.

Upvotes: 0

Views: 136

Answers (3)

Joël Abrahams
Joël Abrahams

Reputation: 381

compareTo Simply looks at the numbers themselves and return 1 if the first is larger, -1 if the second is larger and 0 if they are equal: https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#compareTo(java.lang.Integer)

What you want to is to look at how different the numbers are, and add this to your personal score.

So you could do the following inside the player's class:

int difference = this.personalScore - partner.getPersonalScore(); // positive if your score is greater, else negative or 0 
editScore(this.personalScore + differece);

It's still a bit unclear as to what you want. But I'm assuming that the player has a personalScore int, (or Integer, both are fine, java deals with autoboxing), and a getter getPersonalScore(), which returns this value.

As a sidenote, your write getPersonalScore, but forgot to add brackets. I'm assuming it's a method call (because it starts with get), and these always have brackets at the end: getPersonalScore().

Upvotes: 1

rdhaese
rdhaese

Reputation: 150

It is not that clear what you want to do, if it is comparing two ints, there is a function in the wrapper class Integer:

int compareResult = Integer.compare(this.getPersonalScore(), partner.getPersonalScore);

The compare function return value does not in any case correspond with the difference between the two values that you are comparing. This is explained in the documentation: https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#compareTo(java.lang.Integer)

Often people explain that compareTo() returns -1 for smaller and +1 for larger, but this is not true. The contract states that a value smaller than 0 or larger than 0 will be returned.

For the difference between both you'll have to rely on good old fashioned math. In this case you could do something like this:

int difference = Math.abs(int1 - int2);

and add this after you got the winning player by determining that with the compare funcion.

Upvotes: 2

Yogev Levy
Yogev Levy

Reputation: 335

Maybe something like this?

int winner = Math.max(partner.getPersonalScore(), personalScore);
int loser = Math.min(partner.getPersonalScore(), personalScore);
int d = winner - loser;

Upvotes: 0

Related Questions