Java scope calculation

I have a Java class and am not sure about this problem. We have to make a volume calculator. You enter a sphere diameter, and the program spits out the volume. It works great with integers, but whenever I throw a decimal into it, it falls. Im suggesting that this is due to the accuracy 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, as I said, if I put an integer, it works fine. But I set 25.4 and it falls on me.

+4
source share
2 answers

This is because keyboard.nextInt() expects 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 also write int types and automatically convert them to the desired type.

+8
source
 double sphereDiam; double sphereRadius; double sphereVolume; System.out.println("Enter the diameter of a sphere:"); sphereDiam = keyboard.nextDouble(); sphereRadius = (sphereDiam / 2.0); sphereVolume = ( 4.0 / 3.0 ) * Math.PI * Math.pow( sphereRadius, 3 ); System.out.println(""); System.out.println("The volume is: " + sphereVolume); 
+1
source

All Articles