• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to get different datatypes from a String?  RSS feed

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
my program asks user to input a line of code that has this format: string, int, int, double.
I used a buffered reader, but I do not know how to get each data type, so that I can use them.


Also, what should I do with the IOException?can someone explain it to me?
What is a tokenizer?
 
Greenhorn
Posts: 6
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might be looking for String[] tokens = String.split("\\s"); --\s captures a whitespace
1. check of tokensSize to that of what you need no match continue with next line
2. if token size matches then use iterate over tokens to get expected type using Double.valueOf(String) or Integer.valueOd(String) etc. look for NumberFormatException and continue with next line
3. if you have got all values then apply business logic.

IOException - is checked exception - meaning there is a possibility for it to happen, in this case the input source might not be available to you.

in this case you are supposed to catch it and log it why it has happened.

 
Ranch Hand
Posts: 64
Linux Netbeans IDE Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This sounds like a homework assignment. I don't know if you are suppose to use a java.util.StringTokenizer and some java.lang.Number type's parse* method (eg Integer.parseInt ) or if you can jump right to the java.util.Scanner class. Those should be some starting points.

I recommend the Exception Tutorial and the documentation on java.io.IOException and java.lang.Exception.
 
Marshal
Posts: 56605
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, you should not use StringTokenizer, for reason you will find out when you read its documentation. I would recommend a Scanner; there is an example similar to what you want in the Scanner documentation.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!