【发布时间】:2021-03-11 15:59:43
【问题描述】:
我正在尝试将球体的体积四舍五入到小数点后 1 位,但我不断收到错误消息,提示无法将 String 转换为 double。因此,我没有尝试格式化变量,而是输入了一个数字来尝试查找问题,它仍然说字符串无法转换为双精度。我做错了什么,如何让它将我的变量格式化为小数点后一位?
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);
}
}
【问题讨论】:
标签: java decimalformat