Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

datatype casting doubt

 
Jorge Bendahan
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Harshit Rastogi
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic