Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java sphere volume calculation

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.

like image 570
Curly5115 Avatar asked Dec 26 '22 10:12

Curly5115


1 Answers

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.

like image 164
Marc Baumbach Avatar answered Jan 17 '23 19:01

Marc Baumbach