0

Please help. I am trying to find the batting average and also the on base percentage. My output ends up being 0.0 for both no matter the numbers i put in, but when i use a calculator i end up getting something different. Also in my instructions i am told to input the numbers as integer values and to round my output to the nearest thousandths place.

import java.io.*;
import java.util.*;
public class Prog52d
{
public static void main (String args[])
{
  Scanner kbReader=new Scanner(System.in);
 //input
  System.out.println("Enter Player's Name");
  String name=kbReader.next();
  System.out.println("Enter Number of Times at bat.");
  int timesAtbat=kbReader.nextInt();
  System.out.println("Enter Number of Hits.");
  int hits=kbReader.nextInt();
  System.out.println ("Enter Number of Walks.");
  int walks=kbReader.nextInt();
  //calculates the batting average 
  double battingAverage=hits/timesAtbat;
  battingAverage= Math.round(battingAverage*1000.0)/1000.0;
  //calculates the on base percentage 
  double onBasepercentage= (hits+walks)/(timesAtbat);
  onBasepercentage= Math.round(onBasepercentage*1000.0)/1000.0;

  System.out.println("Player "+name+ " has a ");
  System.out.println("batting average of " + battingAverage + " and");
  System.out.println(" an On Base Percentage of " + onBasepercentage);
}
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
a.p
  • 25
  • 3

3 Answers3

1

You use the code

 double battingAverage = hits / timesAtbat;

where hits and timesAtBat are ints. This invokes int-based division, which will only return int values. Then the int value will be cast to a double.

Since one can't get more hits than times at bat, most people will have a scenario that looks like this

double battingAverage = hits / timesAtbat;
double battingAverage = 30 / 150;
double battingAverage = 0;
double battingAverage = 0.0;

You need to cast the hits and timesAtBat to doubles to get a double-based division.

double battingAverage = ((double)hits) / ((double)timesAtbat);
double battingAverage = ((double)30) / ((double)150);
double battingAverage = 30.0 / 150.0;
double battingAverage = 0.2;

Your other problems are similar.

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138
0

Int/int = int (spoken in types), so you have to either read your Input values as double or convert them afterwards but before the calculation.

The Frozen One
  • 281
  • 2
  • 10
0
 double battingAverage=hits/timesAtbat;

This gives you an integer result because both hits and timeAtbat are integer.

Cast at least one of them to double to promote the datatype of your outcome to double as well:

 double battingAverage = (double)hits / timesAtbat;

Or

 double battingAverage = hits / (double)timesAtbat;
user3437460
  • 17,253
  • 15
  • 58
  • 106