Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

if statement trouble within method  RSS feed

 
Shane McKenzie
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all, hope you can help here. I have no idea what the issue is. here is the code, please advise if you need more....

public void actionPerformed(ActionEvent aE)
{
//create buttonpressed object
Object buttonPressed = aE.getSource();

//figure out which field was entered and
//fill the other two fields accordingly


if (celsiusField.getText() != null && buttonPressed == convert)
{
//grabs input and changes to a double
String inputStr = celsiusField.getText();
double inputTemp = Double.parseDouble(inputStr);

//sets the other fields to the proper calculated value
fahrenheitField.setText("" + TemperatureConverter.CtoF(inputTemp));
kelvinField.setText("" + TemperatureConverter.CtoK(inputTemp));
}


else if (fahrenheitField.getText() != null && buttonPressed == convert)
{
//grabs input and changes to a double
String inputStr = fahrenheitField.getText();
double inputTemp = Double.parseDouble(inputStr);

//sets the other fields to the proper calculated value
celsiusField.setText("" + TemperatureConverter.FtoC(inputTemp));
kelvinField.setText("" + TemperatureConverter.FtoK(inputTemp));

}

else if (kelvinField.getText() != null && buttonPressed == convert)
{
//grabs input and changes to a double
String inputStr = kelvinField.getText();
double inputTemp = Double.parseDouble(inputStr);

//sets the other fields to the proper calculated value
celsiusField.setText("" + TemperatureConverter.KtoC(inputTemp));
fahrenheitField.setText("" + TemperatureConverter.KtoF(inputTemp));
}

I've tested the individual methods (they are statics, in a class called TemperatureConverter), the implementation is ok. The trouble is that in my GUI, the only one that works is the first if, neither of the else ifs work at all, they sinply don't place any data in the other two textAreas. It's driving me mad. Can anyone help me?

shane
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It looks like you're assuming JTextField.getText() will return null if a field is empty. It won't -- it will return the empty String (""). So the first "if" will always be true, and the second two will never have a chance to run.

You want to say

if (celsiusField.getText().length() > 0 && buttonPressed == convert)

etc.
 
Suman Mummaneni
Ranch Hand
Posts: 97
Android Java Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with Ernest


use this

[/CODE]
as a empty text field returns an empty string not a null.

Cheers
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!