I have a Java class and im stumped on this issue. We have to make a volume calculator. You input the diamater of a sphere, and the program spits out the volume. It works fine with whole numbers but whenever I throw a decimal at it, it crashes. Im assuming it has to do with the precision of the variable
double sphereDiam;
double sphereRadius;
double sphereVolume;
System.out.println("Enter the diamater of a sphere:");
sphereDiam = keyboard.nextInt();
sphereRadius = (sphereDiam / 2.0);
sphereVolume = ( 4.0 / 3.0 ) * Math.PI * Math.pow( sphereRadius, 3 );
System.out.println("The volume is: " + sphereVolume);
So, like I said if i put in a whole number, it works fine. But I put in 25.4 and it crashes on me.
This is because keyboard.nextInt()
is expecting an int
, not a float
or double
. You can change it to:
float sphereDiam;
double sphereRadius;
double sphereVolume;
System.out.println("Enter the diamater of a sphere:");
sphereDiam = keyboard.nextFloat();
sphereRadius = (sphereDiam / 2.0);
sphereVolume = ( 4.0 / 3.0 ) * Math.PI * Math.pow( sphereRadius, 3 );
System.out.println("The volume is: " + sphereVolume);
nextFloat()
and nextDouble()
will pickup int
types as well and automatically convert them to the desired type.