The StringTokenizer class is the old way of getting tokens from a String.
The new way is the String class's split() method. However using split() requires you to use regular expressions which can take a while to master.
NormR1
Posting Sage
7,742 posts since Jun 2010
Reputation Points: 1,158
Solved Threads: 793
Skill Endorsements: 16
If you split on the comma each line will give you a two element array. The first element will be the name and second will be the price. It's a String array, so you will then need to parse the price from String to double (or whatever) - the Double class has a method to do that.
JamesCherrill
... trying to help
8,527 posts since Apr 2008
Reputation Points: 2,583
Solved Threads: 1,456
Skill Endorsements: 30
NormR1 is right. the split() method is what you should use, but I'm not sure why he suggests regex here. if you use the comma as separator split(",");, the way JamesCherrill suggests it, you have what you need in the second element of the resulting array. (which yes, you still need to parse to a numerical type, but JamesCherrill already told you how to do that.)
the only thing to keep in mind, is that you'll have to keep the comma as a separator for future lines, and you're not allowed to add titles which have comma('s) in them.
for instance, if you would add,
I, Claudius, 12.35
the price would not be in the second element of the array, but in the third.
you can handle this kind of issue like this:
` String[] info = bookInfo.split(",");`
String price = bookInfo[bookInfo.length-1];
// parse price to a numerical type
stultuske
Industrious Poster
4,382 posts since Jan 2007
Reputation Points: 1,318
Solved Threads: 610
Skill Endorsements: 24
I'm not sure why he suggests regex here
There's no choice, the API doc for String split specifies that the param is a regex.
public String[] split(String regex)
Splits this string around matches of the given regular expression.
fortunately ',' isn't a metachar, so you can split on "," and it works.
JamesCherrill
... trying to help
8,527 posts since Apr 2008
Reputation Points: 2,583
Solved Threads: 1,456
Skill Endorsements: 30
String[] anArray = "Europe on a Shoestring, 10.95".split(",");
System.out.println("anArray=" + Arrays.toString(anArray)); // anArray=[Europe on a Shoestring, 10.95]
System.out.println(">" + anArray[1] + "<"); // > 10.95<
The reason I said a regular expression is required is shown above. The space after the , is included in the second element in the array. The simple regexp: "," leaves the space. To get only the tokens requires a more sophisticated regexp.
NormR1
Posting Sage
7,742 posts since Jun 2010
Reputation Points: 1,158
Solved Threads: 793
Skill Endorsements: 16