【问题标题】:What am I doing wrong in a string to double conversion?我在字符串中做错了什么以进行双重转换?
【发布时间】:2014-12-25 05:44:20
【问题描述】:
几年前上完一门课后,我刚买了一本关于 Java 编码的书。我决定开始编写一个程序来重新开始。无论如何,我计算圆柱体体积的程序有问题。你能批评一下并告诉我发生了什么吗?如果有任何帮助,我正在使用 JCreator。
import javax.swing.*;
public class Cylinder_Volume
{
public static void main (String[] args)
{
string input;
input=JOptionPane.showInputDialog("What is the radius of the cylinder?");
double r;
r=double.parsedouble(input);
input=JOptionPane.showInputDialog("What is the height of the cylinder?");
double h;
h=double.parsedouble(input);
double pi=3.1415926535;
double volume=pi*r*r*h;
System.out.println("The volume of the cylinder is: "+volume+".");
}
}
【问题讨论】:
标签:
java
string
swing
double
【解决方案1】:
2 个错误
1) 是 String 不是 string
2)double.parsedouble 不正确应该是Double.parseDouble
不要忘记java是case sensitive,方法名是camel case
import javax.swing.*;
public class Cylinder_Volume
{
public static void main (String[] args)
{
String input;//first error you have types string //s should be capital
input=JOptionPane.showInputDialog("What is the radius of the cylinder?");
double r;
r=Double.parseDouble(input);//2nd problem
input=JOptionPane.showInputDialog("What is the height of the cylinder?");
double h;
h=Double.parseDouble(input);
double pi=3.1415926535;
double volume=pi*r*r*h;
System.out.println("The volume of the cylinder is: "+volume+".");
}
}
【解决方案2】:
您可能想使用Double.parseDouble(input) 而不是double.parsedouble(input)。
【解决方案3】:
试试
Double.parseDouble(0.0);
将Double 用作对象,而不是原语。对对象的调用,返回原语double。
【解决方案4】:
import javax.swing.*;
public class Cylinder_Volume
{
public static void main (String[] args)
{
String input;
input=JOptionPane.showInputDialog("What is the radius of the cylinder?");
Double r;
r=Double.parseDouble(input);
input=JOptionPane.showInputDialog("What is the height of the cylinder?");
Double h;
h=Double.parseDouble(input);
Double pi=3.1415926535;
Double volume=pi*r*r*h;
System.out.println("The volume of the cylinder is: "+volume+".");
}
}
【解决方案5】:
我认为您的代码应该如下所示:
导入 javax.swing.*;
public class CandidateCode
{
public static void main (String[] args)
{
String input;
input=JOptionPane.showInputDialog("What is the radius of the cylinder?");
double r=Double.parseDouble(input);
input=JOptionPane.showInputDialog("What is the height of the cylinder?");
double h=Double.parseDouble(input);;
double pi=3.1415926535;
double volume=pi*r*r*h;
System.out.println("The volume of the cylinder is: "+volume+".");
}
}
我对其进行了一些更改。
- 是
String 而不是string。
- 要解析 double,您应该使用
Double 类,因为 double 是原始类型。