john smith
john smith

Reputation: 11

stringtokenizer and an unknown variable type

I’m currently working on a project in which I stream in a text document and tokenize it. The only problem is the types in the text document is unknown, is there any way to check what variable type it is before I set it to a variable in the program?

Upvotes: 1

Views: 524

Answers (1)

mgiuca
mgiuca

Reputation: 21357

No, because the type information is not contained in the text stream. For example, imagine the tokeniser encounters the following token:

47

What type does this have? It could be a String ("47"), a byte, an int, a long, a float or a double. All of those types could have produced that token, so there is no way to tell what the type was before it was printed.

When you parse a file, you should already know what types to expect, and give an error if it does not match.

The StringTokenizer class only gives you back Strings. If you are expecting Strings, you can just save them to a variable. If you are expecting another type, you must parse it. For example, if you read the string "47", then you should run it through Integer.parseInt. This will either return an int (e.g., 47), or throw a NumberFormatException if it didn't match. You might want to catch NumberFormatException and give the user an error, since the text file didn't match what you were expecting.

Upvotes: 2

Related Questions