Java球体积计算

时间:2013-01-25 16:33:39

标签: java volume calculator

我有一个Java类,我对此问题感到困惑。我们必须制作音量计算器。您输入球体的直径,程序吐出体积。它适用于整数,但每当我在它上面输入一个小数时,它就会崩溃。我假设它与变量

的精度有关
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);

所以,就像我说如果我输入一个整数,它工作正常。但是我输了25.4并且它在我身上崩溃了。

2 个答案:

答案 0 :(得分:9)

这是因为keyboard.nextInt()期待int,而不是floatdouble。您可以将其更改为:

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()nextDouble()也会提取int类型并自动将其转换为所需类型。

答案 1 :(得分:1)

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