parse example

Hi,

When i ran below example from

http://www.javased.com/?api=java.text.ParsePosition

import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;


public class Parsing {
	public static void main(String[] av) throws ParseException {
		  String input="11 ss";
		  ParsePosition pp=new ParsePosition(0);
		  NumberFormat.getInstance().parse(input,pp);
		  if (pp.getIndex() != (input.length() - 1))   throw new RuntimeException("failed to parse");
		}
}

Open in new window

i am getting below error

Exception in thread "main" java.lang.RuntimeException: failed to parse
      at Parsing.main(Parsing.java:11)

I wonder why i get runtime exception. please advise
LVL 7
gudii9Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jim CakalicSenior Developer/ArchitectCommented:
Hi.

What the code does is get the default Locale NumberFormat instance and uses it to try to parse the input String. The EN_US pattern is something like "###,###.###" where there are some number of digits left and right of the decimal point with comma as the group separator and period as the decimal point. The exact pattern doesn't matter because the input contains non-numeric characters (" ss") that violate the pattern.

When you run this code, it stops parsing the input on the space at position 2. The parse method sets the index of the ParsePosition object supplied to the value 2 (because that's the first character it could not parse) and returns a Number object with the int value 11. So far, everything is just fine and you could go about your business with the parsed value of 11. What the code expects, however, is that it should be able to parse the entire input String as a number, not just part of the value. That's where the  check for pp.getIndex() != (input.length() - 1) comes in. If the check fails, the full String was not parseable as a number, then the RuntimeException is thrown.

Having said that, this particular example contains an error. The only successful parse that avoids an exception is when the input String is some number of pattern characters followed by a single non-pattern character. For example, the values: 123,456x, 33.75y,  3,475.99z, 11% all parse without throwing a RuntimeException. The check for a fully-parseable input should have been pp.getIndex() != input.length() as the parse method sets the index of ParsePosition to the index of the next character to parse when it consumes all the input so if the length of the input is 5 and all the characters are parsed, the ParsePosition.index will be the index 5 (characters at indexes 0-4 were all digits).

Regards,
Jim
Jim CakalicSenior Developer/ArchitectCommented:
Did you have more questions on this topic?
gudii9Author Commented:
sorry i was away few days..let me read few times and let you know
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

gudii9Author Commented:
can you please send me the  code that works without any error similar to above example?
Jim CakalicSenior Developer/ArchitectCommented:
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;


public class Parsing {
	public static void main(String[] av) throws ParseException {
		  String input="11 ss";
		  ParsePosition pp=new ParsePosition(0);
		  Number number = NumberFormat.getInstance().parse(input,pp);
                  System.out.println(number.intValue);
        }
}

Open in new window

gudii9Author Commented:
getting below error from RAD at line 11
intValue cannot be resolved or is not a field
Jim CakalicSenior Developer/ArchitectCommented:
Sorry. My bad. That's intValue(). I forgot the parens
gudii9Author Commented:
i got output
11

if i change my code like below
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;


public class Parsing {
	public static void main(String[] av) throws ParseException {
		  String input="11 ss 13 aa 15";
		  ParsePosition pp=new ParsePosition(0);
		  Number number = NumberFormat.getInstance().parse(input,pp);
                  System.out.println(number.intValue());
        }
}

Open in new window


how do i get
11 13 15
and how do i get
ss aa
please advise
Jim CakalicSenior Developer/ArchitectCommented:
Not sure exactly what you want when you say "how do I get" ... Here's one possible solution to that question which interprets it to mean you want to identify number and non-number values in the input that are separated by whitespace and recombine them into separate Strings again separated by whitespace.

        String input = "11 ss 13 aa 15";
        StringBuilder numbers = new StringBuilder();
        StringBuilder strings = new StringBuilder();
        for (String s : input.split(" ")) {
            ParsePosition pp = new ParsePosition(0);
            Number number = NumberFormat.getInstance().parse(s, pp);
            if (number != null) {
                numbers.append(number).append(" ");
            } else {
                strings.append(s).append(" ");
            }
        }
        System.out.println("Numbers: " + numbers.toString());
        System.out.println("Strings: " + strings.toString());

Open in new window

The output of which is:
Numbers: 11 13 15 
Strings: ss aa 

Open in new window

gudii9Author Commented:
 numbers.append(number).append(" ");
       
                strings.append(s).append(" ");

what above two lines do?
one just prints all numbers other prints all strings by separating with "  "

How the incrementer is increasing after it is being set to 0 as below?

 ParsePosition pp = new ParsePosition(0);
            Number number = NumberFormat.getInstance().parse(s, pp);
Jim CakalicSenior Developer/ArchitectCommented:
Overall what the program does is use NumberFormat's ability to parse tokens (sequences of characters separated by spaces) to determine whether each is a number. If the token is a number (can be parsed so NumberFormat returns a not-null Number object) then the token is appended to the numbers StringBuilder. If it is not the token is appended to the strings StringBuilder. At the end the two StringBuilder contents are printed to show which tokens were numbers and which were not.

>> How the incrementer is increasing ...
ParsePosition is constructed with an index (current parse position of the input) of 0 so NumberFormat knows to start with the first character of the input string. As it parses the input, NumberFormat updates the index in the supplied ParsePosition object to represent its progress. As the javadoc for getIndex() says: "On input to a parse method, this is the index of the character at which parsing will begin; on output, it is the index of the character following the last character parsed." This is how the parse method provides additional information to the client beyond the actual return value of the method.

Jim

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
gudii9Author Commented:
As it parses the input, NumberFormat updates the index in the supplied ParsePosition object to represent its progress.

This happens behind the scenes which we cannot see in the code right?
please advise
Jim CakalicSenior Developer/ArchitectCommented:
That's correct. Internal to NumberFormat (actually DecimalFormat which extends NumberFormat) the code actually doing the parsing modifies the ParsePosition object. You can see one implementation of this at http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b27/java/text/DecimalFormat.java/

Regards,
Jim
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java EE

From novice to tech pro — start learning today.