我一直收到错误" String无法转换为double"我已经尝试将我的变量重新定义为int但这似乎不起作用 - 我只是得到一个标志,说丢失会发生转换为double。我很好奇是否在使用错误的JOptionPane时要求用户输入或者我的变量声明是错误的。
非常感谢任何帮助。
package pf_javaass01c;
import javax.swing.JOptionPane;
public class ConversionCalculator
{
final static String HEADING = "Conversion Calculator";
final static double CONVERSION = 0.6214;
final static double PI = 3.14159;
public static void main(String[] args)
{
// Input Variables
double kilometers, convertedKilometers, miles, convertedMiles;
double width, length, areaRectangle, perimeterRectangle;
double radius, circumference, areaCircle;
// Kilometer to Miles Calculator
kilometers = JOptionPane.showInputDialog(null, "Please enter a kilometer value you wish to convert to miles;", HEADING, JOptionPane.QUESTION_MESSAGE);
convertedKilometers = kilometers * CONVERSION;
JOptionPane.showMessageDialog(null, kilometers + " kilometers is equal to " + convertedKilometers + " miles.", HEADING, JOptionPane.INFORMATION_MESSAGE);
} // End of main
} // End of ConversionCalculator
答案 0 :(得分:0)
JOptionPane
返回的值为String
。您正尝试将该值放入kilometers
,double
。你基本上试图将球体装入三角形孔中。结果,发生了错误。
解决方案是简单地解析,或将字符串转换为double。为此,请致电Double.parseDouble()
:
// get the user input and put it into a string variable first
String userInput = JOptionPane.showInputDialog(null, "Please enter a kilometer value you wish to convert to miles;", HEADING, JOptionPane.QUESTION_MESSAGE);
// parse the user's input and assign the result to kilometers
kilometers = Double.parseDouble(userInput);
答案 1 :(得分:0)
Double.parseDouble()是新变量的答案,允许用户输入转换为double!