File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes datatype casting doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "datatype casting doubt" Watch "datatype casting doubt" New topic
Author

datatype casting doubt

Jorge Bendahan
Ranch Hand

Joined: Apr 11, 2008
Posts: 82
Hello, here is the situation, i have a jtextField, in this component I can input any primitive datatype, but this datatype is wrapped into a String, for example: typed in the word "true" in the component, even if it is actually a boolean datatype, first its wrapped into a String, the thing is how do i write a method that receives this String and determines what kind of datatype it actually is
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

You have to decide on the rules for what constitutes a particular type and write code to parse the input.

If you know what the underlying data type should be, and the mapping between the input and the datatype is one-to-one, this is easy. For example: a boolean type could be "true", "y", "yes", "1" etc. In the case of Booleans you could use the Boolean.parseBoolean() or valueOf() methods. Both will evaluate garbage as false however, so if you want more control you could look at regular expressions.

If you have one input and any possible data type you have a far harder problem. Is this what you have?


JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Harshit Rastogi
Ranch Hand

Joined: Apr 15, 2008
Posts: 131
like for Boolean the solution is mentioned above. Simlarily you can parse the value by Using Integer,String,Double class mehtods valueOf() .The code has to be surrnounded in try-catch block. If the parsing (conversion) of value throws an exception just ignore it in the catch block and try parsing it with the other type.

code:
--------------------------------------------------------------------------------


Object getValue(String value)
{
try{
return Integer.valueOf(value)
}catch(Exception e ){ // if exception occurs try for the other type.
}
try{
return String.valueOf(value)
}catch(Exception e ){
}
}


--------------------------------------------------------------------------------

Something like this can help.


My Techie Blog - Java Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: datatype casting doubt