问题描述
我正在尝试将球体的体积四舍五入到小数点后一位,但我不断收到错误消息,指出字符串无法转换为双精度。因此,我没有尝试格式化变量,而是输入一个数字来尝试查找问题,但它仍然说字符串无法转换为双精度值。我做错了什么,如何将我的变量格式化为一位小数?
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));