Double.parseDouble(String) : Problem to parse large String

Hello,
I need to convert A String to a Double in my application without rounding of digits.
I have used the Double.parseDouble(String) method.
The maximum string length can be 17 including dot(.)
So if my String is (of length 17)
Eg.
S= �9999999999.999999� then I am getting the double value as
d= 9999999999.999998(compare the last digit)
If s = �9999999999.111111� then d = 9999999999.111110
If s = �9999999999.555555� then d = 9999999999.555555 (result that I want)
If s = �9999999999.666666� then d = 9999999999.666666 (result that I want)
If s = �9999999999.777777� then d = 9999999999.777777 (result that I want)
If s = �9999999999.888888� then d = 9999999999.888887
If s = �9999999999.999999� then d = 9999999999.999998
If s = �9123456789.123456� then d = 9123456789.123456
But string length up to 16 is giving me the accurate result
So any body can explain me that why it is happening? And how can i get the accurate result.
Thanks in advanced.

Hi,
Thank You for your suggestion. By which i can store
the big double number in Data base , but at some
point i require to parse a double value from a Double
reference.In that case if the Decimal value length
=> 16 then it the last digit changes or rounds.
coverting 9999999999.999999 Decimal value to double
value. It gives me 9999999999.999998 and
9999999999.9999999 gives me the 10000000000.0000000.
but the Double value 999999999.999999 is ok
and 999999999.99999999 rounds.Err, is there a follow up question in there?

Similar Messages

  • Facing Problem in parsing a string to date

    Hi,
    I was trying to change a string into date with date format ("EEEE,MMM,d,h:mm") but I always get the year as 1970.
    here is my code
    String strDate="Saturday,Jan 19 7:31";
    String dateFormat3="EEEE,MMM,d,h:mm";
         try {
         DateFormat myDateFormat = new SimpleDateFormat(dateFormat3);
         result1=myDateFormat.parse(strDate);
    catch(ParseException pe) {
                System.out.println("ERROR: could not parse date in string \"" +
            }any solution for it.

    This is my actual code
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;
    public class TestingDate {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              String dateFormat="EEEE, MMM d h:mm a";
              Date test=new Date(2007,0,19, 19, 31);
              System.out.println(" original date is "+test);
              String stringResult=DateToString(test,dateFormat);
              System.out.println("Date to string is "+stringResult);
              Date dateResult=stringToDate(stringResult,dateFormat);
              System.out.println(" String to date is "+dateResult);
              String stringResult2=DateToString(dateResult,dateFormat);
              System.out.println(" Date to string  is "+stringResult2);
    public static String DateToString(Date test, String dateFormat) {
             String result = null;
             try {
                  DateFormat myDateFormat = new SimpleDateFormat(dateFormat);
                     result = myDateFormat.format(test);
                     //System.out.println(" reslut date is "+result);
              } catch (Exception e) {
                   System.out.println(" Exception is "+e);
              return result;
    public static Date stringToDate(String strDate,String dateFormat1){
         Date result1=null;
         try {
              DateFormat myDateFormat = new SimpleDateFormat(dateFormat1);
              result1=myDateFormat.parse(strDate);
         catch(Exception e){
              System.out.println(" exception is "+e);
         return result1;
    }I am facing problem in getting the actual date. Please suggest the solution.

  • Problem with parsing large XML files chunked over HTTP

    I'm trying to isolate a bug that was introduced when upgrading the JRE in use from Java 7u51 to 7u71 without changing any code. The problem appears to be very similar to: Bug ID: JDK-8027359 XML parser returns incorrect parsing results.
    Further investigation showed that it was also introduced in the same versions (7u71) where that fix was applied. Unlike that bug though, my XML is marked as version 1.0. It also appears to be with only large XML files, on the order of 10MB or so.
    The closest I've been able to narrow it down to is the code is using JAXB to unmarshall a stream that the debugger tells me is a org.apache.http.com.EofSensorInputStream / org.apache.http.impl.io.ChunkedInputStream. The exception I get is not consistent, but typically appears to be from chunks being overwritten or shuffled, resulting in letters appearing in attributes that are actually numbers, or like the following where an attribute "testAttribute" gets partially overwritten by the end of a timestamp that was in a different section of the XML.
    javax.xml.bind.UnmarshalException
    - with linked exception:
    [javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,98748]
    Message: Attribute name "testAttribu00Z" associated with an element type "testElement" must be followed by the ' = ' character.]
      at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.handleStreamException(UnmarshallerImpl.java:421)
      at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:357)
      at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:334)
    Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,98748]
    Message: Attribute name "testAttribu00Z" associated with an element type "testElement" must be followed by the ' = ' character.
      at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:598)
      at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(StAXStreamConnector.java:181)
      at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:355)
      ... 6 more
    Here's some code that seems to reproduce it if you can connect to an XML server that returns a large chunked XML file:
      SchemeRegistry registry = new SchemeRegistry();
      registry.register(
                    new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
      HttpClient client = new DefaultHttpClient(new BasicClientConnectionManager(registry));
      String url = "http://someUrlReturningAlargeChunkedXML";
      HttpGet method = new HttpGet(url);
      HttpResponse response = client.execute(method);
      InputStream inputStream = response.getEntity().getContent();
      XMLStreamReader responseReader = factory.createXMLStreamReader(inputStream);
      JAXBElement<JaxBObjectOfResponse> wot = unmarshaller.unmarshal(responseReader, JaxBObjectOfResponse.class);
    If you connect using URL.openStream() to the same service there is no error. If I read bytes directly and write to a file, there is no error. The error only happens when I try to unmarshal it, and it's large, and I'm using Java 7u71 (or later). It can be consistently repeated with the jsp webapp that I'm using, but didn't show the error when I used the same code with a Wikipedia dump XML file.
    How can I unmarshal in a different way to avoid this problem? Or, how can I better isolate the bug so it can be posted to the appropriate bug system?

    Apparently, adding the Woodstox XML libraries avoids the bug. Is there anyone who can reproduce this on another system? Was there any changes to the Stax implementation between u67 and u71 that may have introduced a bug like this?
    Edit: When setting the logging level to DEBUG, I once saw the overwritten buffer being logged as if that was what was received (as in the testAttribu00Z example above). I can't repeat that anymore though, and very rarely it does parses with no exception (though it may have still been corrupted). Now the error seems to be consistently on one of the buffer boundaries, as in:
    17:08:09,705 DEBUG wire:63 - << "2000[\r][\n]"
    17:08:09,705 DEBUG wire:77 - << "trend>....OTHER XML...<trend hours=""
    17:08:09,705 DEBUG wire:77 - << "634.0972777777778" datetime="2013-05-21T00:43:48.350Z" t"
    17:08:09,705 DEBUG wire:63 - << "[\r][\n]"
    17:08:09,705 DEBUG wire:63 - << "2000[\r][\n]"
    17:08:09,705 DEBUG wire:77 - << "rend-mode="0">
    Exception in thread "main" java.lang.NumberFormatException: t34.0972777777778
      at com.sun.xml.internal.bind.DatatypeConverterImpl._parseDouble(DatatypeConverterImpl.java:213)
      at mypackage.Trend_JaxbXducedAccessor_hours.parse(TransducedAccessor_field_Double.java:48)
      at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StructureLoader.startElement(StructureLoader.java:194)
      at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:486)
      at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:465)
      at com.sun.xml.internal.bind.v2.runtime.unmarshaller.InterningXmlVisitor.startElement(InterningXmlVisitor.java:60)
      at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXStreamConnector.handleStartElement(StAXStreamConnector.java:231)
      at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(StAXStreamConnector.java:165)
      at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:355)
      at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:334)
    Or:
    17:19:12,563 DEBUG wire:63 - << "2000[\r][\n]"
    17:19:12,563 DEBUG wire:77 - << ...OTHER XML...<trend index="5"
    17:19:12,563 DEBUG wire:77 - << "" label="N"
    17:19:12,563 DEBUG wire:63 - << "[\r][\n]"
    Exception in thread "main" java.lang.NumberFormatException: Not a number: N
      at com.sun.xml.internal.bind.DatatypeConverterImpl._parseInt(DatatypeConverterImpl.java:106)
      at com.sun.xml.internal.bind.DatatypeConverterImpl._parseShort(DatatypeConverterImpl.java:118)

  • Performance Problem in parsing large XML file (15MB)

    Hi,
    I'm trying to parse a large XML file(15 MB) and facing a clear performance problem. A Simple XML Validation using the following code snippet:
    DBMS_LOB.fileopen(targetFile, DBMS_LOB.file_readonly);
    DBMS_LOB.loadClobfromFile
    tempCLOB,
    targetFile,
    DBMS_LOB.getLength(targetFile),
    dest_offset,
    src_offset,
    nls_charset_id(CONSTANT_CHARSET),
    lang_context,
    conv_warning
    DBMS_LOB.fileclose(targetFile);
    p_xml_document := XMLType(tempCLOB, p_schema_url, 0, 0);
    p_xml_document.schemaValidate();
    is taking 30 mins on a HP-UX (4GB ram, 2 CPU) machine (Oracle version : 9.2.0.4).
    Please explain what could be going wrong.
    Thanks In Advance,
    Vineet

    Thanks Mark,
    I'll open a TAR and also upload the schema and instance XML.
    If i'm not changing the track too much :-) one more thing in continuation:
    If i skip the Schema Validation step and directly insert the instance document into a Schema linked XMLType table, what does OracleXDB do in such a case?
    i'm getting a severe performance hit here too... the same file as above takes almost 40 mins to Insert.
    code snippet:
    DBMS_LOB.fileopen(targetFile, DBMS_LOB.file_readonly);
    DBMS_LOB.loadClobfromFile
    tempCLOB,
    targetFile,
    DBMS_LOB.getLength(targetFile),
    dest_offset,
    src_offset,
    nls_charset_id(CONSTANT_CHARSET),
    lang_context,
    conv_warning
    DBMS_LOB.fileclose(targetFile);
    p_xml_document := XMLType(tempCLOB, p_schema_url, 0, 0);
    -- p_xml_document.schemaValidate();
    insert into INCOMING_XML values(p_xml_document);
    Here table INCOMING_XML is :
    TABLE of SYS.XMLTYPE(XMLSchema "http://INCOMING_XML.xsd" Element "MatchingResponse") STORAGE Object-
    relational TYPE "XDBTYPE_MATCHING_RESPONSE"
    This table and type XDBTYPE_MATCHING_RESPONSE were created using the mapping provided in the registered XML Schema.
    Thanks,
    Vineet

  • Problem with parsing large xml files

    Hello All,
    I am parsing a large xml file of 20MB and I use DocumentBuilder.parse(File). This method works for small xml files with size less than 20MB but the application hangs and doesn't through any error message when parsing 20MB xml files. Please let me know what I have to do at this point ?
    Thanks & Regards,
    Kumar.

    Well... i can't agree.
    If you have such structure:
    <task>
      <task/>
      <task>
         <task>
            <task/>
         </task>
         <task/>
      </task>
    </task>
    ...you may always keep stack of tasks (at startElement push to top, and at endElement pop), so at every leaf of tree you will have all parents of that leaf.
    for such structure:
    <task id="1" parent="0"/>
    <task id="2" parent="1"/>
    <task id="3" parent="1"/>
    <task id="4" parent="2"/>
    <task id="5" parent="3"/>
    ...it will be much faster to go thro document by sax several times to build tree of tasks, than to load all document into memory...

  • Problems parsing a string

    Hi,
    I'm having a problem with parsing a string. Basically, I want to take a string for example: "TomWentToTheShop" and divide it into a coherent sentence (Tom went to the shop).
    I've started the code by breaking the string into a char array, and if the character is a capital then store the index in the array and then do a substring.
    But I don't think this is the best way to solve the problem, if anyone has any ideas it would be greatly appreciated.
    thanks.
    char[] charRequestTypeArray = string.toCharArray();
    for (int i = 1; i < (charRequestTypeArray.length -1); i++) {
    char c = charRequestTypeArray;
    if (Character.isUpperCase(c)) {
    Arrays.fill(storeCapitalIndex, i);
    else{
    Arrays.fill(storeNonCapitalIndex, i);

            String s = "TomWentToTheShop";
            System.out.println(s.charAt(0) + s.substring(1).replaceAll("((?<!^)[A-Z])", " $1").toLowerCase());or even just        System.out.println(s.charAt(0) + s.substring(1).replaceAll("([A-Z])", " $1").toLowerCase());Edited by: sabre150 on Nov 11, 2007 9:40 PM

  • Problem in Coverting XML String into Document

    Hi,
    I am getting some problem while parsing a String XML in to Document object.
    CODE :
    public static Document converDocument(String xml){
    DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;
    try {
    builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
    e.printStackTrace();
    Document document = null;
    try {
    document = builder.parse(new InputSource(new StringReader(xml)));
    System.out.println("Document is after parsing ====>>>"+document);
    } catch (SAXException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    } catch (IOException e1) {
    e1.printStackTrace();
    return document;
    The xml which I am passing is :
    <?xml version="1.0" encoding="UTF-8"?>
    <note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>abc</body>
    </note>
    It is giving the document as null;
    Can anybody please help?
    Regards,
    sheeetal.

    >
    Vikas Sridharan wrote:

    >       CALL TRANSFORMATION ('ID')
    >       SOURCE XML = lv_output_str "<============ ERRONEOUS = HERE
    >       RESULT ref = <fst_dyn_table> .
    >
    Remove the "=" sign, this code will work :
          CALL TRANSFORMATION ('ID')
          SOURCE XML lv_output_str
          RESULT ref = <fst_dyn_table> .

  • Double.parseDouble(String) - problems when string is in scientific notation

    Hello guys,
    I'm doing some numerical calculations and I wonder whether it is possible for Double.parseDouble(String) to parse string in the scientific notation i.e. 1.0824234234E-10. Is it the notation itself causing the exception : NumberFormatException or the number is just too big/small and double can't hold it ?
    If it's just the notation how can I fix it ?
    Regards

    i'm not quite sure whether double odoes not allow it.
    perhaps consider the api Double.valueOf() and the testing code provided; reproduced below:To avoid calling this method on a invalid string and having a NumberFormatException be thrown, the regular expression below can be used to screen the input string:
            final String Digits     = "(\\p{Digit}+)";
      final String HexDigits  = "(\\p{XDigit}+)";
            // an exponent is 'e' or 'E' followed by an optionally
            // signed decimal integer.
            final String Exp        = "[eE][+-]?"+Digits;
            final String fpRegex    =
                ("[\\x00-\\x20]*"+  // Optional leading "whitespace"
                 "[+-]?(" + // Optional sign character
                 "NaN|" +           // "NaN" string
                 "Infinity|" +      // "Infinity" string
                 // A decimal floating-point string representing a finite positive
                 // number without a leading sign has at most five basic pieces:
                 // Digits . Digits ExponentPart FloatTypeSuffix
                 // Since this method allows integer-only strings as input
                 // in addition to strings of floating-point literals, the
                 // two sub-patterns below are simplifications of the grammar
                 // productions from the Java Language Specification, 2nd
                 // edition, section 3.10.2.
                 // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
                 "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+
                 // . Digits ExponentPart_opt FloatTypeSuffix_opt
                 "(\\.("+Digits+")("+Exp+")?)|"+
           // Hexadecimal strings
           "((" +
            // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
            "(0[xX]" + HexDigits + "(\\.)?)|" +
            // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
            "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +
            ")[pP][+-]?" + Digits + "))" +
                 "[fFdD]?))" +
                 "[\\x00-\\x20]*");// Optional trailing "whitespace"
      if (Pattern.matches(fpRegex, myString))
                Double.valueOf(myString); // Will not throw NumberFormatException
            else {
                // Perform suitable alternative action
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Double.html

  • Large string into the VARCHAR2 field parsing problem

    Guys,
    SQL> select * from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
    PL/SQL Release 10.2.0.4.0 - Production
    CORE 10.2.0.4.0 Production
    TNS for Solaris: Version 10.2.0.4.0 - Production
    NLSRTL Version 10.2.0.4.0 - Production
    My problem is: The frontend of the application sends a large string into the VARCHAR2 (4000 BYTES) field.
    The string it sends is somewhat like the samples given below. I need to parse and put them in the tables
    as shown below. Please let me know, if you have any questions. -
    Crit: Some text1.
    Proficient (points 2): Some more text1.
    Comment1...........................................
    ..Comment1
    Crit: Some text2.
    Non-performance (points 0): Some more text2.
    Crit: Some text3.
    Distinguished (points 3): Some more text3.
    Crit: Some text4.
    Distinguished (points 3): Some more text4.
    Table 1
    Crit          points          comment        morecomment
    Some text1.     2           Some more text1. Comment1.............................Comment1
    Some text2.     0           Some more text2.
    Some text3.     3           Some more text3.
    Some text4.     3           Some more text4.
    Table 2
    Overall Comment
    Crit: Some text1.
    Proficient (points 2): Some more text1.
    Crit: Some text2.
    Non-performance (points 0): Some more text2.
    Crit: Some text3.
    Distinguished (points 3): Some more text3.
    Crit: Some text4.
    Distinguished (points 3): Some more text4.
    Overall comments:
    Blah2 Blah2 Blah2!
    Some more blah2 blah2 blah2.
    Table 1
    Crit          points          comment        morecomment
    Some text1.     2           Some more text1.
    Some text2.     0           Some more text2.
    Some text3.     3           Some more text3.
    Some text4.     3           Some more text4.
    Table 2
    Overall Comment
    Blah2 Blah2 Blah2!
    Some more blah2 blah2 blah2.
    Crit: Some text1.
    Proficient (points 2): Some more text1.
    Comment1...........................................
    ..Comment1.
    Crit: Some text2.
    Non-performance (points 0): Some more text2.
    Comment2...............................Comment2.
    Crit: Some text3.
    Distinguished (points 3): Some more text3.
    Crit: Some text4.
    Distinguished (points 3): Some more text4.
    Overall comments:
    Blah1 Blah1 Blah1!Some more blah1 blah1 blah1.
    Table 1
    Crit          points          comment        morecomment
    Some text1.     2           Some more text1. Comment1.............................Comment1
    Some text2.     0           Some more text2. Comment2...............................Comment2.
    Some text3.     3           Some more text3.
    Some text4.     3           Some more text4.
    Table 2
    Overall Comment
    Blah1 Blah1 Blah1!Some more blah1 blah1 blah1.--------------------------------------------------------------------
    My code which doesn't work
    WITH t AS
    (SELECT 'Crit: Some text1.
    Proficient (points 2): Some more text1.
    Crit: Some text2.
    Non-performance (points 0): Some more text2.
    Crit: Some text3.
    Distinguished (points 3): Some more text3.
    Crit: Some text4.
    Distinguished (points 3): Some more text4.
    Overall comments:
    Blah2 Blah2 Blah2!
    Some more blah2 blah2 blah2.' string
    FROM   dual)
    SELECT SUBSTR(REGEXP_SUBSTR(string,'Crit: +$', 1, level), 12) "Crit",
           SUBSTR(REGEXP_SUBSTR(string,'points [^\)]+', 1, level), 8) "points",
           SUBSTR(REGEXP_SUBSTR(string,'\):^[[:alnum:]]+$', 1, level), 3) "comment",
           SUBSTR(REGEXP_SUBSTR(string,'^[[:alnum:]]+$', 1, level), 1) "morecomment"
    FROM   t
    CONNECT BY LEVEL <= (LENGTH(string) - LENGTH(REPLACE(string, 'Crit:')))/5
    WITH t AS
    (SELECT 'Crit: Some text1.
    Proficient (points 2): Some more text1.
    Comment1...........................................
    ..Comment1
    Crit: Some text2.
    Non-performance (points 0): Some more text2.
    Crit: Some text3.
    Distinguished (points 3): Some more text3.
    Crit: Some text4.
    Distinguished (points 3): Some more text4.' string
    FROM   dual)
    SELECT SUBSTR(string, INSTR(string, 'Overall comments:', -1) + 18) "overall_comment"
    FROM   t
    CONNECT BY LEVEL <= (LENGTH(string) - LENGTH(REPLACE(string, 'Crit:')))/5Edited by: abyss on Sep 17, 2010 12:26 PM

    Hi,
    Except for the morecomment column, you almost had it.
    Oracle documentation often refers to ^ and $ as meaning beginnig- and end-of-line, but they seem to mean beginning- and end-of-string.
    Aside from that , I just changed a few details (like ' +' to '.+').
    SELECT SUBSTR (REGEXP_SUBSTR (string, 'Crit:.+',          1, level), 6, 18)     AS Crit,
           SUBSTR (REGEXP_SUBSTR (string, 'points [^\)]+',           1, level), 8    )     AS points,
           SUBSTR (REGEXP_SUBSTR (string, '\):[ [:alnum:]]+',      1, level), 3     )     AS cmnt,
           REGEXP_REPLACE ( SUBSTR ( REGEXP_SUBSTR ( string || CHR(10) ||'Crit:'
                                                         , '.*?Crit:'
                                          , 1
                                          , LEVEL + 1
                                          , 'n'          -- . matches newline
                              , LENGTH ( REGEXP_SUBSTR ( string
                                                                , 'Crit:.*'
                                               , 1
                                               , LEVEL
                                      ) +
                              LENGTH ( REGEXP_SUBSTR ( string
                                                , 1
                                                , LEVEL
                                      ) - 2
                    , 'Crit:$'
                       ) more_cmnt
    FROM   t
    CONNECT BY LEVEL <= (LENGTH(string) - LENGTH(REPLACE(string, 'Crit:')))/5
    ; This gets the results you requested from the data you posted. I don't know if it gets those results for the right reasons or not, since you didn't post any reasons for why you want those results. Always explain why you want the results you do, giving specific examples from the sample data.
    The morecomment (called more_cmnt above) is much more complicated, since it involves scanning across multiple lines. I wouldn't be surprised if there is a simpler way than what I posted above.
    I do not recommend doing this in pure SQL. I suggest a PL/SQL function, because debugging and maintenance would be so much easier.
    To populate table2:
    WITH     got_pos         AS
         SELECT     string
         ,     INSTR (string, 'Overall comments:', -1)     AS pos
         FROM     t
    SELECT  SUBSTR ( string
                , pos + 18
                )     AS overall_comment
    FROM    got_pos
    WHERE     pos     > 0
    ;

  • Is there a problem on the pattern of SimpleDateFormat to parse a String ?

    Hello,
    I tried to parse a String to a Date using a SimpleDateFormat.
    I must be able to have on the pattern something like : "yyyyMMdd_HH00".
    To get a String from a Date with SimpleDateFormat.format(Date date) it works well, but when a try to parse a String into a Date with SimpleDateFormat.parse(String date) I get a : java.text.ParseException: Unparseable date.
    I try it on a JVM 1.4 and 1.5 for the same result.
    An exemple of code :
              String pattern = "yyyyMMdd_HH00";
              SimpleDateFormat currentFormat = new SimpleDateFormat(pattern);
              Date date = currentFormat.parse("20091223_1000");It seems that adding the '00' after 'HH' raise the exception...
    Has the 'HH00' a particular meaning like on Oracle 'HH24' ?
    Is there a way to add number after the 'HH' ?
    Thanks
    Edit :
    Oh yeah, I forgot, I tryied to use the pattern "yyyyMMdd_HH'00'" using '' to escape the 00 without better result...
    Edited by: Jeremy.Antonucci on 23 déc. 2009 15:25

    The context of this pattern :
    To get a file on a http server, I must build an Url String with a filename using the current date.
    I want to be able to change easily the pattern on a file parameters.
    The date must be ending with 00 for the minutes.
    I may have use a pattern with 'HHmm' and suppress the minutes but if it is change on the futur the code will not work...
    As I can't say if in the futur the url will change for the date pattern or not, I decide to use a pattern like "yyyyMMdd_HH00" that works fine for everything else than parsing a string.
    I create a String date based on the current date on UTC using this pattern and keep it to use it to compose an Url String.
    After I need to know how much time I must sleep before the next execution (on each Hour), so I use this date +1 hour to see if the currentDate during this calculation is higher than this date+1... (I'm surely not clear, but it is not the real problem just for curious ^^)
    A dirty solution is to avoid this problem is to catch this case and do substitution on a temporary pattern of the 'HH00' with 'HHmm'. It's really dirty because nothing says that later a 'HH00' mean always 'HHmm' but I have nothing better...
              String pattern2 = pattern;
              if (pattern.matches(".*HH00$")) {
                   pattern2=pattern.substring(0, (pattern.length()-2))+"mm";
              }Where can I do this bug report ?
    Do you see a good solution ?

  • Parsing and String tokenizer

    I am trying to use String Tokenizer to extract fields from a file then do a calculation on some of the fields.
    My problem is when I try to parse the strings that need the calculations I get error codes as shown at the end of post. I don't see why the parsing shouldn't work.( error codes are class expected and incompatable types)
    // ParsingTextFile.java: Process text file using StringTokenizer
    import java.io.*;
    import java.util.StringTokenizer;
    public class ParsingTextFile1 {
      /** Main method */
      public static void main(String[] args) {
       // Declare  buffered file reader and writer streams
       BufferedReader brs = null;
       BufferedWriter bws = null;
       //declare tokenizer
       StringTokenizer tokenizer;
       // Declare a print stream
       PrintWriter out = null;
        // Five input file fields:total string, student name, midterm1,
        // midterm2, and final exam score
        String line=null;
        String sname = null;
       String mid1= null;
        String mid2 = null;
        String finalSc = null;
      /  double midterm1 = 0;
        double midterm2 = 0;
        double finalScore = 0;
        // Computed total score
        double total = 0;
        try {
          // Create file input and output streams 
          brs = new BufferedReader(new FileReader("in.dat"));
          bws = new BufferedWriter(new FileWriter("out.dat"));
         while((line= brs.readLine())!=null){
         tokenizer =new StringTokenizer(line);
          sname = tokenizer.nextToken();
          mid1 = tokenizer.nextToken();
          mid2 = tokenizer.nextToken();
          finalSc= tokenizer.nextToken();
          midterm1 = double.parseDouble(mid1)//this code not working
          midterm2 = double.parseDouble(mid2);)//this code not working
          finalScore = double.parseDouble(finalScore);//this code not working
          out = new PrintWriter(bws);
          total = midterm1*0.3 + midterm2*0.3 + finalScore*0.4;
          out.println(sname + " " + total);
        catch (FileNotFoundException ex) {
          System.out.println("File not found: in.dat");
        catch (IOException ex) {
          System.out.println(ex.getMessage());
        finally {
          try {
            if (brs != null) brs.close();
            if (bws != null) bws.close();
          catch (IOException ex) {
            System.out.println(ex);
    }[\code]
    errorsC:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:43: class expected
        midterm1 = double.parseDouble(mid1);
                          ^
    C:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:44: class expected
        midterm2 = double.parseDouble(mid2);
                          ^
    C:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:45: class expected
        finalScore = double.parseDouble(finalScore);
                            ^
    C:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:43: incompatible types
    found   : java.lang.Class
    required: double
        midterm1 = double.parseDouble(mid1);
                         ^
    C:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:44: incompatible types
    found   : java.lang.Class
    required: double
        midterm2 = double.parseDouble(mid2);
                         ^
    C:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:45: incompatible types
    found   : java.lang.Class
    required: double
        finalScore = double.parseDouble(finalScore);
                           ^
    6 errors
    Process completed.

    while(line.hasMoreTokens())
    sname = tokenizer.nextToken();  
       mid1 = tokenizer.nextToken();   
      mid2 = tokenizer.nextToken();  
       finalSc= tokenizer.nextToken(); 
        midterm1 = double.parseDouble(mid1)//this code not working
         midterm2 = double.parseDouble(mid2);)//this code not working  
       finalScore = double.parseDouble(finalScore);//this code not working
    }if it doesn't work then you need to add delimiter Or the token that you are trying to convert into is not valid.

  • Parsing a string using StringTokenizer

    Hi,
    I want to parse a string such as
    String input = ab{cd}:"abc""de"{
    and the extracted tokens should be as follows
    ab
    cd
    "abc""de"
    As a result, I used the StringTokenizer class with deilmeter {,},:
    StringTokenizer tokenizer = new StringTokenizer(input,"{}:", true);
    In this was, I can separate the tokens and also can get the delimeters. The problem is I don't know how to parse the string that has double quote on it. If a single quote " is taken as a delimeter then
    ", abc, ",", de," all of them will be taken as a separate token. My intention is to get the whole string inside the double quote as a token including the quotes on it. Moreover, if there is any escape character "", it should be also included in the token. Help please.
    Thanks

    A bit of a "sticky tape"-solution...
    import java.util.StringTokenizer;
    public class Test {
        public static void main(String[] args) {
            String input = "ab{cd}:\"abc\"\"de\"";
            StringTokenizer st = new StringTokenizer(input, "{}:", true);
            while(st.hasMoreTokens()) {
            String token = st.nextToken();
            if(token.startsWith("\"") && token.endsWith("\"")) {
            token = token.substring(1,token.length()-1);
                System.out.println(token);
    }

  • Large string array in 6.1 is extremely slow

    Good day all,
    While this is in to tech support at NI, I wanted to see if anyone else has encountered it.
    I am upgrading from 6.0.2 to 6.1. Several large (2500 rows by 250 columns or larger) string arrays are used as inputs into subvi's. Under 6.0.2, these functions run in tenths of seconds, while under the converted 6.1 vi's they run in 20 seconds or more!
    Tracing back using probes, the problem is occurring at the point of the input. It is appears that the array is taking many seconds to copy from the input to the wire on the diagram.
    Array controls generated in 6.1 (not converted from 6.0.2) seem to function just fine. Using a save with options... to convert back to 6.0.2, the vi's again function in tenths of
    seconds.
    Anyone have any ideas?
    Thanks!

    I hear what you're saying about legacy code...
    Something you might want to be looking at for the future is migrating to a structure where the data is stored in a 1D array, where each element is a cluster contain the data that's now in a single row. This would be the most straight-forward change, but could make getting at the data tricky, depending on how you need to be able to search it.
    Alternately, you could have a cluster containing arrays of each of the row values.In this structure element 0 of all the arrays is the first "row", element 1 of the arrays is the second "row" and so on. This structure at first blush looks more complicated, but it's really not, plus it would allow you to use any value (or combination of
    values) to search for a specific row without a lot of parsing.
    If the data that is in the example VIs you posted is typical, either of these changes would be advantagous because it looks like there is a lot of reptative data that might be able to be encoded in an enum. Plus storing numbers as numbers often reduces the memory required and produces a predictable memory footprint (an I32 will always take-up 4 bytes per value regardless of how large of small the number is). My sense is that the variability of the string size is what's killing you.
    One thing that would make this sort of dramatic change somewhat easier is that because you are changing the basic datatype of the interface, you aren't going to have to worry about finding all the places the change will effect--the wires will be broken.
    If you ever decide to take this on, give a hollar.
    Mike...
    Certified Professional Instructor
    Certified LabVIEW Architect
    LabVIEW Champion
    "... after all, He's not a tame lion..."
    Be thinking ahead and mark your dance card for NI Week 2015 now: TS 6139 - Object Oriented First Steps

  • Getting char values from a string problem

    Hi,
    Here's an example of what I'm trying to do:
    boolean loopSwitch = true;
    while (loopSwitch)
         String orderDecider = JOptionPane.showInputDialog (null, "Would you like your numbers to be ordered in   ascending or descending order(A/D)",      "Order decision", JOptionPane.QUESTION_MESSAGE);
         if (orderDecider == A)
         loopSwitch = false;
         }I basically want the user to input either a/A/d/D and to get the char values from the string so I can use them in an if statement.
    Basically, I wanna parse the string into a char.
    Is this possible?
    Thanks.
    Edited by: xcd on Oct 16, 2009 8:38 AM

    Why not just use the String.equals() method to compare a String to a String?
    But if you must, you can use the String.charAt() method to return a char at a particular location in the String.
    Note: char literals need to be surrounded by single quotes ('A') and String literals need to be surrounded by double quotes ("A").

  • Very large string to internal text table

    Hi,
    I have a string that contains all the information read from a flat file and I want to put all that information in an internal table where each row is just 1024 char in order to contain a row of the original flat file.
    In the string I can recognize the special character "carriage return" in order to separate identify each row but now my problem is that I don't know can I parse the string text.
    Can you help me please?

    hi marshal ,
    do like this first read the internal table and replace the all occurencse of carriage return with '#'  and split the string
    at '#'.
    constant : c_enter type c ,
                  c_hash  type c value '#' ..
    data:
      BEGIN OF wa_text ,
              text(1024) TYPE c,
      END OF wa_text.
      i_text LIKE STANDARD TABLE OF wa_text.
    REPLACE ALL OCCURRENCES OF c_enter
                IN wa_text WITH c_hash.
    SPLIT wa_text AT c_hash INTO: str1 str2 str3,
                              TABLE i_text.
    regards,
    sandeep
    Edited by: Sandeep patel on Jul 14, 2008 12:43 PM

Maybe you are looking for