0

I'm trying to create a short program for my Java class that requires me to calculate the batting average of a player. For some reason when I go to divide the two variables I get 0.0 even though the user enters in data. I added print statements to try and debug my code but the numbers are appearing after the user enters them but they aren't dividing when I pass them to battingAvg. Can anyone else spot my error?

import java.util.Scanner;

public class Problem42 {

    public static void main(String[] args) {

        //Keyboard input for hits & number of at-bats
        Scanner numberOfHits = new Scanner( System.in);
        System.out.print("How many hits does the batter have?");
        int hits = numberOfHits.nextInt();

        System.out.println(hits);

        Scanner numberOfBats = new Scanner( System.in);
        System.out.print("What is the batters number of at-bats?");
        int atBats = numberOfBats.nextInt();

        // Calculating the batting average
        double battingAvg = (hits) / (atBats);

        System.out.println(battingAvg);
        //Eligibility for the All Stars Game
        if (battingAvg > .300) {
            System.out.println("Player is eligible for All Stars Game.");
        } else { 
            System.out.println("Player is ineligible for All Stars Game.");
        }

        numberOfHits.close();
        numberOfBats.close();
    }

}
Rodrigo Gomes
  • 346
  • 1
  • 5
Saverio
  • 99
  • 7
  • Sorry but I did not know what was causing the problem so I am unable to search for a question pertaining to "Double division behaving wrongly" when I didn't realize it was an issue with the double variable. – Saverio Sep 24 '15 at 03:49

1 Answers1

-1
double battingAvg = (hits) / (atBats);

Since hits and atBats is interger, integer division is happening. Caste any one of them to double to get a double result.

double battingAvg = hits / (double)atBats;
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307