• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

TextField returning String problem

 
Mikey Greene
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there I have a problem that seems straight forward but the answer eludes me. I have done some Java (SE) but am dabbling with J2ME.

I am trying to write a program that calculates the total cost of a journey by entering miles, mpg and cost of fuel etc.

I have got a problem with a textfield and converting the returning String to an int. I can get it to return a value that is typed in to the textfield but when it tries to return the contents of an empty textfield (ie nothing typed in there) a NumberFormatException is thrown.

The following code is a section of the program that I would expect to run without problem but doesnt.



I have tried replacing the if statement with various values ie milesStVal=="" and milesStVal==" " and milesStVal==null but nothing changes.

What is returned when using the getString() method of a texfield? I assume it would either be "" or null? As I say adding these data types to the if statement doesnt seem to make any difference.

Any advice would be appreciated

Thanks in advance.

Cheers

Mike
 
Kj Reddy
Ranch Hand
Posts: 1704
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Change your if loop.

From:
if(milesStVal==""){
milesStVal="0";
}

To:

if(milesStVal == null || milesStVal.trim().length() == 0) {
milesStVal="0";
}

or

if(milesStVal == null || milesStVal.trim().equals("")) {
milesStVal="0";
}
 
Kj Reddy
Ranch Hand
Posts: 1704
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Mikey Greene:

I have tried replacing the if statement with various values ie milesStVal=="" and milesStVal==" " and milesStVal==null but nothing changes.



Never use "==" to compare strings equality. User String.equals() or String.equalsIgnorecase() method to compare Strings equality.

Hope it works.
 
Mikey Greene
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi KJ thanks a lot. Of course!

Thanks for the very fast reply as well.

Nice one

Mike
 
fred rosenberger
lowercase baba
Bartender
Posts: 12196
35
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is probably also a beginner question, as it is not specific to the J2ME. any additional followups should be there.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic