Reputation: 49
I need this application to convert the number entered by the user in the JTextField
into celsius and display it in a JLabel
. It seems to be having problems parsing the the data entered into a double? This is one error among many.
Can anyone help me figure out whats wrong? (I've only entered double values in the text field when testing it out and it still wont change it to a double.)
public class TempConvertGUI extends JFrame{
private JLabel result;
private final JTextField input;
public TempConvertGUI()
{
super("Fahrenheit to Celsius Application");
setLayout(new FlowLayout());
//TempConvert convert=new TempConvert();
input=new JTextField(10);
input.setToolTipText("Enter degrees in fahrenheit here.");
input.addActionListener(new ActionListener()
{
private double temp;
private String string;
@Override
public void actionPerformed(ActionEvent event) {
if(event.getSource()==input)
{
remove(result);
if(event.getActionCommand()==null)
result.setText(null);
else
{
temp=Double.parseDouble(event.getActionCommand());
string=String.format("%d degrees Celsius", convertToCelsius(temp));
result.setText(string);;
}
add(result);
}
}
});
add(input);
result=new JLabel();
add(result);
}
private double convertToCelsius(double fahrenheit)
{
return (5/9)*(fahrenheit-32);
}
}
Upvotes: 3
Views: 89
Reputation: 2649
It seems you got this exception
java.util.IllegalFormatConversionException: d != java.lang.Double
And it is because of this line of code
string=String.format("%d degrees Celsius", convertToCelsius(temp));
%d
represents an integer; you want to use %f
for a double (convertToCelsius
returns a double).
So change it to
string=String.format("%f degrees Celsius", convertToCelsius(temp));
Upvotes: 2
Reputation: 8348
temp=Double.parseDouble(input.getText());
)%f
to parse floating point valuesresult
JLabel in ActionPerformed, it has already been added to the UI - just set it's text(5/9)
is integer math, if you want floating point math then specify one of the numbers as the proper data type: (5/9d)
Upvotes: 3
Reputation: 1742
Instead of temp=Double.parseDouble(event.getActionCommand());
, you should be parsing the input from input.getText()
.
Upvotes: 0