如何解决十进制格式说“字符串不能转换为双精度”
我正在尝试将球体的体积四舍五入到小数点后一位,但我不断收到错误消息,指出字符串无法转换为双精度。因此,我没有尝试格式化变量,而是输入一个数字来尝试查找问题,但它仍然说字符串无法转换为双精度值。我做错了什么,如何将我的变量格式化为一位小数?
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);
}
}
解决方法
public class Pokecard {
private String cardName; //Name of the Pokemon
private String cardType; //Type of the card (Pokemon)
private String pokemonType; //Type of the Pokemon (Example: Grass)
private int hitPoints; //Hit points of the Pokemon
private String pokemonAttacks; //What attacks the pokemon has
private int cardNumber; //Number of the card (Example: 1)
public void setPokemon(String name,String type,String pType,int hp,String attacks,int number) {
this.cardName = name;
this.cardType = type;
this.pokemonType = pType;
this.hitPoints = hp;
this.pokemonAttacks = attacks;
this.cardNumber = number;
}
}
返回一个 DecimalFormat.format
。但是您将其分配给 String
变量。
将语句更改为:
double
在收到此类错误时,请阅读该方法可用的 javadoc 并检查返回类型/参数类型是否与您指定的匹配。
,DecimalFormat.format() 方法返回一个字符串。您可以通过 Double.parseDouble() 方法将其解析使其翻倍。
double volumeOfSphere2 = Double.parseDouble(df.format(1.1111111));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。