Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you calculate percentages in Java?

Tags:

java

math

So I am trying to make a game with a health bar for the player but whenever I use cross products or any other method of math that should work the percentage result is 0.0... Here is the .java file that handles this:

package com.game.graphics;

import com.game.entity.mob.Mob;

public class HUD {
    Mob target;
    Sprite healthbar;
    Sprite bgBar;

    double percent_normal;

    public HUD(Mob target) {
        this.target = target;
        bgBar = new Sprite(0xff777777, 104, 8);
        healthbar = new Sprite(0xffFF0000, 100, 6);
    }

    public void update() {
        percent_normal = target.getHealth() / 100;
        percent_normal *= target.getMaxHealth();
    }

    public void printData() {
        System.out.println("Normal(" + percent_normal + ")");
    // if the targets's health is any lower than the max health then this seems to always return 0
    }

    public void render(Screen s) {
        s.renderSprite(5, 5, bgBar, false);
        s.renderSprite(7, 6, new Sprite(0xffFF0000, (int) percent_normal, 6), false);
    }
}

I'm not sure if my Math is completely off or if I'm going about this horibly wrong. I've tried looking up how to calculate it to no avail so that's why I'm putting this question here.

like image 207
draco miner Avatar asked Dec 05 '22 02:12

draco miner


1 Answers

Your way of calculating the percentage seems to be off. To calculate the percentage of X compared to Y you have to do:

double result = X/Y;
result = result * 100;

So in this case your code should look like

public void update() {
    percent_normal = target.getHealth() / target.getMaxHealth();
    percent_normal *= 100;
}

The reason you are always getting 0.0 although is because of the int 100. I believe the target.getHealth()/100 will return a value that is in the form of 0.x and will be turned into int 0 before being cast to double.

like image 198
ThomasS Avatar answered Dec 06 '22 18:12

ThomasS