javadividebyzeroexception

java: how to find a value in which initial value is zero and getting error "/ by zero"


I need to calculate accuracy in my java game. So far, I tried several methods however, everytime it either doesn't work or gives me an error "/ by zero". The initial value for bullets_shot is zero and the formula for accuracy is enemies_downed % bullets_shot. How can I bypass this error while getting an accurate read for accuracy? I tried doing a loop where it sets bullets_shot to 1 if it is 0 but it wouldn't give an accurate reading. Is there a way in which I can set a value in place for it until it has a value greater than 1 and if so how would I do so? Here are some code snippets. here is the full code: https://github.com/ms12r/Galaxy-Monkeys

In the tick method of the enemy class:

if(tempObject.getId() == ID.Bullet)
        {
            if(getBounds().intersects(tempObject.getBounds()))
                {
                    hp -= 50;
                    bullets_hit += 1;
                    handler.removeObject(tempObject);

and in the mouseinput class

for (int i = 0; i < handler.object.size(); i++)
    {
        GameObject tempObject = handler.object.get(i);

        if(tempObject.getId() == ID.Player)
        {
            handler.addObject(new Bullet(tempObject.getX()+16,
                    tempObject.getY()+24, ID.Bullet, handler, x, y, game));
            bullets_shot += 1;

        }

in the game class

            System.out.println("GAME OVER");
            System.out.println("Level Reached: " + game.level);
            System.out.println("Accuracy: " + ((Enemy.bullets_hit + Gorilla.bullets_hit) % MouseInput.bullets_shot) + "%");
            Game.INSTANCE.stop();           }

Solution

  • You could create a simple method called bulletAcuracy() like the following

    public static double bulletAcuracy(int bulletHits, int totalBulletsFired)
    {
        if(totalBulletsFired == 0)
            return 0;
    
        return bulletHits/((double)totalBulletsFired);
    }
    

    Then call it in main like so

    System.out.println("Accuracy: " + bulletAcuracy(Enemy.bullets_hit + Gorilla.bullets_hit, MouseInput.bullets_shot) + "%");