4

我有一个 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,它在我身上崩溃了。

4

2 回答 2

9

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

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类型并自动将它们转换为所需的类型。

于 2013-01-25T16:35:26.010 回答
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);
于 2015-10-16T19:50:01.620 回答