Java球体体积计算

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时,它会崩溃。


8
nextInt()只解析整数吗? - Gene
2个回答

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


2
或者,如果您想坚持使用double类型,您可以调用nextDouble()函数,并将sphereDiam保持为一个double类型。 - Marc Baumbach
非常感谢!真有趣,我之前尝试过这个方法但没成功。可能是我打错了。再次感谢!! - Curly5115

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

1
不要只是贴出可用的代码作为答案。解释一下原帖中的问题以及如何修复它,然后(如果必要)再将可用的代码放入您的答案中。 - brimborium

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接