Java 十进制格式,表示“小数”;字符串不能转换为双引号;
我试图将球体的体积四舍五入到小数点后1位,但我一直收到一个错误,即字符串不能转换为双精度。因此,我没有尝试格式化一个变量,我只是输入了一个数字来尝试查找问题,它仍然表示字符串不能转换为double。我做错了什么?如何将变量的格式设置为小数点后一位Java 十进制格式,表示“小数”;字符串不能转换为双引号;,java,decimalformat,Java,Decimalformat,我试图将球体的体积四舍五入到小数点后1位,但我一直收到一个错误,即字符串不能转换为双精度。因此,我没有尝试格式化一个变量,我只是输入了一个数字来尝试查找问题,它仍然表示字符串不能转换为double。我做错了什么?如何将变量的格式设置为小数点后一位 import java.util.*; import java.util.InputMismatchException; import java.lang.Math.*; import java.text.DecimalFormat; public c
import java.util.*;
import java.util.InputMismatchException;
import java.lang.Math.*;
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double diameter;
DecimalFormat df = new DecimalFormat("#.#");
//User Input Section
while (true) {
System.out.print("What is the diameter of the sphere (cm): ");
try {
diameter = input.nextDouble();
break;
} catch (InputMismatchException mme) {
System.out.println("Please enter a number in number format (e.x. 1, 55, 6)");
input.nextDouble();
}
}
double radius = diameter/2;
double radiusCubed = radius * radius * radius;
double radiusSquared = radius * radius;
double fourOverThree = 4/3;
double volumeOfSphere = fourOverThree * Math.PI * radiusCubed;
double volumeOfSphere2 = df.format(1.1111111);
double surfaceAreaOfSphere = 4 * Math.PI * radiusSquared;
System.out.print("The volume of the sphere is " + volumeOfSphere2);
}
}
DecimalFormat.format
返回一个字符串
。但是您正在将其分配给一个双变量
将声明更改为:
stringvolumeofsphere2=df.format(1.1111111);
收到此类错误时,请阅读该方法可用的javadoc,并检查返回类型/参数类型是否与您指定的匹配。DecimalFormat.format()方法返回字符串。您可以通过double.parseDouble()方法将其解析为double
double volumeOfSphere2 = Double.parseDouble(df.format(1.1111111));