【问题标题】:Decimal Format Saying "String cannot be converted to double"十进制格式说“字符串不能转换为双精度”
【发布时间】: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


    【解决方案1】:

    DecimalFormat.format 返回一个String。但是您将其分配给 double 变量。

    把语句改成:

    String volumeOfSphere2 = df.format(1.1111111);
    

    收到此类错误时,请阅读该方法可用的 javadoc,并检查返回类型/参数类型是否与您指定的匹配。

    【讨论】:

      【解决方案2】:

      DecimalFormat.format() 方法返回一个字符串。您可以通过 Double.parseDouble() 方法将其 解析 加倍。

      double volumeOfSphere2 = Double.parseDouble(df.format(1.1111111));
      

      【讨论】:

        猜你喜欢
        • 2015-06-14
        • 2014-05-05
        • 2019-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-13
        • 2019-08-31
        • 2019-07-22
        相关资源
        最近更新 更多