aspose file tools*
The moose likes Beginning Java and the fly likes TextField returning String problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "TextField returning String problem" Watch "TextField returning String problem" New topic
Author

TextField returning String problem

Mikey Greene
Greenhorn

Joined: Oct 05, 2005
Posts: 7
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

Joined: Sep 20, 2003
Posts: 1704
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

Joined: Sep 20, 2003
Posts: 1704
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

Joined: Oct 05, 2005
Posts: 7
Hi KJ thanks a lot. Of course!

Thanks for the very fast reply as well.

Nice one

Mike
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11320
    
  16

This is probably also a beginner question, as it is not specific to the J2ME. any additional followups should be there.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: TextField returning String problem