Curly5115
Curly5115

Reputation: 93

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.

Upvotes: 4

Views: 38781

Answers (2)

Adumuah Dowuona
Adumuah Dowuona

Reputation: 121

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);

Upvotes: 1

Marc Baumbach
Marc Baumbach

Reputation: 10473

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.

Upvotes: 9

Related Questions