This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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
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?
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.