Fixed-length numbers and strings

Hello,
I have to make a critical decision about API usage. I would be grateful if some of you could share their experiences. This will help me make an informed decision and avoid potential trouble further down the line.
I have to use fixed-length integer numbers and fixed-length strings such as for example:
-A string that is exactly 5-letter long (no longer and no shorter than 5 letters). e.g. "abcde"
-A number that is exactly 8-digit long (no longer and no shorter than 8 digits). e.g. "12345678"
Ideally I would get some sort of exception when the "container" for the letters or digits contains less or more than what the spec says.
I am not sure which classes or primitives could meet my needs. As far as the fixed-length string is concerned I initially thought of using a array of chars but an array of chars is not that easy to manipulate and contains "garbage" until you explicitely fill it in with data. I'd rather some sort of class.
Can anyone please advise me?
Thanks in advance,
Julien.

Why not use the same thing like in the case of the String
/**Warning: this is an example and not very good design.*/
public class FixedInteger {
   private int min, max;
   private int value;
   public int getValue() { return value;}
   public void setValue(int v) {
        if (v >= min && v < max) {
            throw new Exception();
        value = v;
   /**ex. min = 10000, max = 100000 for 5 digit numbers*/
   public FixedInteger(int min, int max, int value) {
       this.min = min; this.max = max;
       setValue(value);
}You can do tricks like convert it to immutabla like the String and Integer class in the Java Api
Edited by: szgy on Oct 5, 2007 2:22 PM

Similar Messages

  • TO_NUMBER function on varchar2 column with numbers and strings

    I need to create a column in a view that converts a varchar2 column data to number. The problem is that some
    of the data have strings and some numbers. I get "ORA-01722: invalid number" error when Oracle tries to covert
    strings (e.g. 'ABCD') to number. What I need is to get a NULL value if the data is an invalid number.
    How can I rewrite the following to get NULL value is a string is invalid number?
    select to_number('abcd') numberColumn
    from dual
    thanx
    Alfred

    SQL> select * from test_char_num;
    ALPHA_NUM
    ABC
    DEF
    123
    234
    A12
    SQL> select decode(NVL(length(trim(translate(alpha_num, '1234567890', ' '))), 0),
      2                0, alpha_num, 'NULL') new_alpha_num
      3  from test_char_num;
    NEW_ALPHA_
    NULL
    NULL
    123
    234
    NULLP.S I am printing 'NULL' just to show the result, Please replace the 'NULL string with NULL value in SQL.
    Thx,
    Sri

  • Extracting multiple variables of different fixed length from a string ( Java )

    Dear all,
    I am expecting an input string of
    NationalBroadCastTony12245tv0930113024213tv0820230022214tv0915140024213rd10002300
    I need to display it in the following format:
    Telecastor: NationalBroadCast
    Presenter:Tony
    ch_code
    pg_code
    source
    start_time
    end_time
    1
    2245
    tv
    0930
    1130
    2
    4213
    tv
    0820
    2300
    2
    2214
    tv
    0915
    1400
    2
    4213
    rd
    1000
    2300
    I know the starting and ending position of Telecastor, and Presenter in the input string. I also know the position of the start element of the table(starting of the loop). I also know the length of a single row( allows me to contruct the loop). I reckon regex is probably not the best way since there is no pattern matching. I am looking at some sort of a config driven logic.
    Are there any java string function that I can use together with some form of config driven configuration that anyone can suggest?
    I am looking along the line of some configuration like eg
    telecastor 17
    Presentor  4
    pg_code 4 ( anything after character 21 is the loop)
    source 2
    start_time 4
    end_time 4
    For example another input I can expect is
    ElementaryScienceAccessment223-Feb-131500-1730RegentHallE32344390E21235487A23443564G23443246
    I need to display as
    Exam:ElementaryScience
    Nature: Accessment2
    Date:23-Feb-13
    Time:1500-1730
    Venue:RegentHall
    Student ID
    Score
    E323443
    90
    E212354
    87
    A234435
    64
    G234432
    46
    Exam:17
    Nature:11
    Date:9
    Time:9
    Venue:10
    Student ID:7 (anything after 56 is a loop)
    Score:2
    Unfortunately the input stream is not in XML format. What sort of string function/config driven logic can I use to allow me to define a 1 config fits all mechanism?

    Are there any java string function that I can use together with some form of config driven configuration that anyone can suggest?
    Well there is the obvious one: the 'substr' method of the String class.
    http://docs.oracle.com/javase/6/docs/api/java/lang/String.html
    Your 'config' would be the list of start/end or start/length values for each of the components.
    The usual parsing issue is knowing how to determine when one element ends and the next one starts. For this fragment of yours:
    12245tv
    How do you know if the first component, 'ch_code', is '1', '2', or '122'?

  • Help with FIXED LENGTH columns - using spool command

    Hi guys,
    I have a view I am trying to spool using fixed length columns, and the spacing is off. Ive tried numerous things such as specifiying the column width before running the query, using the rpad command, but nothing seems to work. I have to spool it to a text file in order for the users to import this file into another system. I would welcome any and all suggestions. Thanks so much. The following is the view:
    SELECT "EMPLOYEE_ID","FIRST NAME","INITIAL","LAST NAME","SUFFIX","TRAINING DATE","Course ID","Class ID", "We", "Make / Model", "Cali", "Barrell", "Serial Number", "Qualification", "Application", "SCORE", "Status", "Add Time", "Record Add ID","Record Add Date","Record Change ID","Record Change Date","RN" FROM
    (SELECT
    UPPER(RPAD(tbl.ssn,10)) AS "EMPLOYEE_ID",
    UPPER(RPAD('',12)) AS "FIRST NAME",
    UPPER(RPAD('',1)) AS "INITIAL",
    UPPER(RPAD('',20)) AS "LAST NAME",
    UPPER(RPAD('',5)) AS "SUFFIX",
    UPPER(RPAD(to_char(QUALDATE, 'mmddyyyy'),8)) AS "TRAINING DATE",
    UPPER(RPAD('P123',8)) AS "Course ID",
    UPPER(RPAD('',6)) AS "Class ID",
    UPPER(RPAD('P',4)) AS "We",
    UPPER(RPAD('',4)) AS "Make / Model",
    UPPER(RPAD('',4)) AS "Cali",
    UPPER(RPAD('',7)) AS "Barrell",
    UPPER(RPAD('',15)) AS "Serial Number",
    UPPER(RPAD('A',4)) AS "Qualification",
    UPPER(RPAD('D',4)) AS "Application",
    to_char((RAWSCORE/250)*100, 'fm000.00') AS "SCORE",
    UPPER(RPAD('PASS',4)) AS "Status",
    UPPER(RPAD('',8)) AS "Add Time",
    UPPER(RPAD('',8)) AS "Record Add ID",
    UPPER(RPAD('',8)) AS "Record Add Date",
    UPPER(RPAD('',8)) AS "Record Change ID",
    UPPER(RPAD('',8)) AS "Record Change Date",
    row_number()over(partition by firearms_scores.ID_NUMBER order by QUALDATE desc ) rn
    FROM FIREARMS_scores, TBL
    where scores.id_number=tbl.id_number
    and qualyear='2010' and coursecode='SA'
    order by employee_id)
    where rn =1

    Hi,
    You RPAD doesn't do anything, since they are same as:
    SQL> SELECT NULL AS "Record Add ID",
      2         NULL AS "Record Add Date",
      3         NULL AS "Record Change ID",
      4         NULL AS "Record Change Date" FROM DUAL;
    R R R R
    SQL>Can't see why COLUMN command shouldn't do what you want. Maybe you forgot the double quotes?
    SQL> COL "Record Add ID" FOR a18
    SQL> COL "Record Add Date" FOR a18
    SQL>
    SQL> SELECT NULL AS "Record Add ID",
      2         NULL AS "Record Add Date",
      3         NULL AS "Record Change ID",
      4         NULL AS "Record Change Date" FROM DUAL;
    Record Add ID      Record Add Date    R R
    SQL>P.S: You probably shouldn't set a column width which is smaller than the header length
    Regards
    Peter

  • BPC 7.5 NW -- Data Manager Export:  Fixed-Length Fields?

    Hi Experts,
    Client has a requirement that we export a batch of transaction data from BPC, which is generally no problem, but in this case they want to do it with Fixed-Length fields in the Export file.
    I've done a lot of BPC Data Manager Imports with Fixed-Length fields, and that function really works well.  But, has anyone tried to use the Export package with this option?  It doesn't seem to be working in my case yet.
    Any tips?
    Thanks so much, as always,
    Garrett
    =======================
    Update -- After going back to review documentation, it looks like the the *PAD() function is actually intended for export not really importing, which makes sense.  ...The SAP online help library says that it's meant for import, but I now believe that is a typo.
    Also, I've added the line "OUTPUTFORMAT = NORMAL" in my *OPTIONS section.  Anyone else manage to get export working on BPC 7.5 NW
    Edited by: Garrett Tedeman on Mar 3, 2011 1:37 PM

    Update -- This problem may now be resolved.
    I have been able to conduct test IMPORTs of 48,000, then 96,000 and then 1.7 million records.  All were fine.
    It turns out that that difference is that the text files were sorted by amount in the ones that failed.  They were sorted by GLAccount in column A for the ones that succeeded.
    Edit:  Yep, all files loaded normally when re-sorted by GLACCOUNT, etc. on the left-hand side.  Apparently, when you're doing a lot of records that might confuse the system or something
    Edited by: Garrett Tedeman on Nov 18, 2010 11:41 AM

  • Need to download a file which si space delimted and has fixed length char

    Hi,
    I have a custom report which downloads an output file in text format.I need the contents to be space delimited.My file data contains numbers as well as characters.I ahve pased the parameter WRITE_FIELD_SEPARATOR = ' ' in the FM.Hwoever the space is introduced only oif the column value is a character.If its a number/digit,the columns are not seperated by space.
    Now my data appears like that:
    0000101310179.28 +0827200808 DHLBSRF VISA AUG 2008US021SW111 RYAN,BICOVNY
    I want my data to be like this :
    0000101310 179.28 + 0827200808 DHLBSRF VISA AUG 2008 US02 1SW111 RYAN,BICOVNY
    DO I need to pass any additinal parametre?Also for fixed length characrets,do i need to pack/unpack data before passing to the FM ?
    Thanks.

    Hi,
    try this way.
    REPORT ztest_notepad.
    DATA: BEGIN OF it_download OCCURS 0,
           data TYPE string,
          END OF it_download.
    DATA: BEGIN OF it_vbrk OCCURS 0,
            vbeln TYPE vbrk-vbeln,
            fkart TYPE vbrk-fkart,
            fktyp TYPE vbrk-fktyp,
            netwr TYPE vbrk-netwr,
          END OF it_vbrk.
    DATA : l_netwr TYPE char21.
    "START-OF-SELECTION.
    START-OF-SELECTION.
      SELECT  vbeln
              fkart
              fktyp
              netwr
       FROM vbrk
       INTO CORRESPONDING FIELDS OF TABLE it_vbrk
       UP TO 100 ROWS.
      LOOP AT it_vbrk.
        l_netwr = it_vbrk-netwr.
        CONCATENATE it_vbrk-vbeln
                    it_vbrk-fkart
                    it_vbrk-fktyp
                    l_netwr
            INTO it_download-data
            SEPARATED BY space.
        APPEND it_download.
        CLEAR  it_download.
      ENDLOOP.
      CALL FUNCTION 'GUI_DOWNLOAD'
           EXPORTING
                filename = 'C:\test.txt'
                filetype = 'ASC'
           TABLES
                data_tab = it_download.
    Thanks
    Venkat.O

  • Reading fixed length flatfile & splitting it into header and lineitem data

    Hi Friends,
    I am reading a fixed length flat file from application server into an Internal table.
    But problem is, data in flat file is in the below format with fixed start and end positions.
    1 - 78 -  control header
    1 - 581 - Invoice header data
    1 - 411 - Invoice Line item data
    1 - 45 -   trailer record
    There will be one control header and one trailer record per file and number of invoice headers and its line items can vary.
    There is unique identifiers to identify as below.
    Control header - starts with 'CHR'
    Invoice Header starts with - '000'
    Invoice Lineitem stats with - '001'
    trailer record - starts with 'TRL'
    So its like
    CHR.......control  data..(79)000.....header data...(660)001....lineitem1...(1481)001...lineitem2....multiples of 411 and 581 and ends with... TRL...trailer record..
    (position)
    I am first reading the data set and store in internal table with a field of 255char.
    by looping on above ITAB i have to split it into Header records and line item records.
    Did anyone face this kind of scenario before. If yes appreciate if you can throw some ideas on logic to split this data.
    Any help in splitting up the data is highly appreciated.
    Regards,
    Simha
    ITAB declaration
    DATA: BEGIN OF ITAB OCCURS 0,
                   FIELD(255),
               END OF ITAB,
                lt_header type table of ZTHDR,
                lt_lineitem type table of ZTLINITM.

    Hi,
    i am sending sample code which resembles your requiremeant.
    data: BEGIN OF it_input OCCURS 0, "used for store all the data in one line.
          line type string ,
          END OF it_input,
          it_header type TABLE OF string WITH HEADER LINE,"use to store all header with corresponding items
          it_item   type TABLE OF string WITH HEADER LINE.."used to store all item data
    CALL FUNCTION 'GUI_UPLOAD'
      EXPORTING
        filename                      = 'd:\test.txt'
      FILETYPE                      = 'ASC'
      HAS_FIELD_SEPARATOR           = ' '
      HEADER_LENGTH                 = 0
      READ_BY_LINE                  = 'X'
      DAT_MODE                      = ' '
      CODEPAGE                      = ' '
      IGNORE_CERR                   = ABAP_TRUE
      REPLACEMENT                   = '#'
      CHECK_BOM                     = ' '
      VIRUS_SCAN_PROFILE            =
      NO_AUTH_CHECK                 = ' '
    IMPORTING
      FILELENGTH                    =
      HEADER                        =
      tables
        data_tab                      = it_input
    EXCEPTIONS
      FILE_OPEN_ERROR               = 1
      FILE_READ_ERROR               = 2
      NO_BATCH                      = 3
      GUI_REFUSE_FILETRANSFER       = 4
      INVALID_TYPE                  = 5
      NO_AUTHORITY                  = 6
      UNKNOWN_ERROR                 = 7
      BAD_DATA_FORMAT               = 8
      HEADER_NOT_ALLOWED            = 9
      SEPARATOR_NOT_ALLOWED         = 10
      HEADER_TOO_LONG               = 11
      UNKNOWN_DP_ERROR              = 12
      ACCESS_DENIED                 = 13
      DP_OUT_OF_MEMORY              = 14
      DISK_FULL                     = 15
      DP_TIMEOUT                    = 16
      OTHERS                        = 17
    IF sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    LOOP AT  it_input.
       write : it_input-line.
    ENDLOOP.
    before doing the below steps just takethe controle record and trail record cutt of from the table input based up on the length
      split it_input-line AT '000' INTO TABLE it_header IN CHARACTER MODE.
      LOOP AT  it_header.
        split it_header AT '0001' INTO TABLE it_item IN CHARACTER MODE.
        write :/ it_header.
      ENDLOOP.
    after this you need to cut the records in tocorresponding  fields in to respective tables by putting loop on item and header table as i decleared above.
    i think this may solve your problem you need to keep some minnor effort.
    Regaurds,
    Sree..

  • A better way of building the fixed-length String

    I created the following code to build a fixed length string. I checked other posts for the same topic, but I found mine is better. The code below converts a double numeric value to a fixed length string with padding of white spaces (or other types):
    Line 15 initializes the char array to while space; line 13 creates a character array; lines 17, 18 copy the array created in line 13 to the one initialized in line 15.
    Any comment is welcomed.
    1. import java.text.*;
    2.
    3. public class jformat {
    4.
    5. public static void main(String[] args) {
    6.
    7. char[] fb=new char[14];
    8. char[] tb;
    9. int c, f;
    10. DecimalFormat fmt=new DecimalFormat("########0.00");
    11. double dbl=12345.66;
    12.
    13. tb=fmt.format(dbl).toCharArray();
    14.
    15. for(c=0; c<fb.length; c++) fb[c]=' ';// this line is not required in JDK 1.5
    16.
    17. for(c=tb.length-1, f=fb.length-1; c>=0; c--, f--){
    18.     fb[f]=tb[c];
    19. }
    20. System.out.println(new String(fb));
    21.
    22. }
    23.
    24. }

    Here's a couple of alternatives. One uses a StringBuffer and the second, for Java 5 only, uses the Formatter capabilities.
    import java.text.DecimalFormat;
    public class jformat
        public static void main(String[] args)
            int fieldSize = 14;
            double dbl = 12345.66;
            String dblString = new DecimalFormat("0.00").format(dbl);
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < fieldSize - dblString.length(); j++)
                sb = sb.append(' ');
            System.out.println(sb.append(dblString).toString());
             *  The above code works in Java versions 1.3, 1.4, and 1.5.
             *  However, 1.5 provides the Formatter class, and the single
             *  line below can replace the preceeding code.
            System.out.printf("%14.2f%n", dbl);
    }

  • Header data in xml tags and line items in fixed length but both in same fil

    Hi,
    In my scenario target side in header level i am passing all the values are fixed values and line item vaues are getting from the source data.how to write udf for this scenario.It should be graphical mapping.
    Please help to me
    please reply fast
    Thanks&Regards
    Swathi
    Edited by: SWATHIP on Feb 4, 2011 7:16 AM

    Hi,
    1) If your values are numerical you can use the "FormatNum" function under Arithmetic Functions.
    This will help you fix the length of the number and even the decimal part.
    2) If you want to fix the length of field which is of type string, you can try the following code:
    public String setLength(String var1, String var2,  Container container) throws StreamTransformationException
         /*   var1 will have the String Value, in var2 pass a constant integer of fixed length you want  */
         int len = Integer.parseInt(var2);
         String rslt = var1;
         if( var1.length() < len)
             for(int i = var1.length(); i < len; i++)
                 rslt = rslt + " "; // appending space
         else
               rslt = rslt.substring(0,var1.length - 1)l
         return rslt;
    regards,
    Aravind
    Edited by: ajnayak on Feb 7, 2011 7:25 AM

  • How to map xml to a fixed length string?

    Hi All,
    I have a requirement to map request xml to a string of fixed length and format:
    For eg,
    Source:
    <Person>
    <Name>George</Name>
    <Age>21</Age>
    </Person>
    Target:
    String of format
    Name : 8 chars
    Age : 2chars.
    so the required mapping should result in
    "George 21".
    Note: 2 blanks after "George" to allow for 8 characters. Is this kind of mapping possible using ALSB xquery? I have tried to create a MFL representation for the string , and used it in the xquery as the targer but it is generating
    "George21".Only data present in source is getting mapped :(

    My advice would be to use MFL transformation for that.
    Documentation about MFL can be found at edocs: http://edocs.bea.com/alsb/docs26/fbhelp/index.html
    Find tips and tricks about ALSB at my blog: http://dev2dev.bea.com/blog/jordinho/

  • Open Hub - Fixed Length KF With Appended 0 and only 10 Char

    Hi-
    I have a requirement to create a fixed length file following the layout below and I am unable to get the KF (LFE-AMOUNT) correct.  The Open Hub destination takes on the length of the object which in this case for key figure (0AMOUNT) is 17 (15 w/ 2 decimal).  That said, even if I do a sub-string of it on the TRFN to the Open Hub, I will still have an output length of 17.  I tried creating a new object but it kept dropping the decimal.  Is there an easy way to do this in the TRFN via an ABAP routine?  Again, I just need the KF 10 characters padded with 0 on left side. 
          05 LFE-CUST-ID PIC X(13).                         (13 Chars)
          05 LFE-AMOUNT PIC 9(08)V99.                  (10 Chars)
          05 LFE-EFF-DATE PIC X(06).                     (6 Chars)
          05 LFE-RETURN-CODE           PIC X(03).     (3 Chars)
    Need:
    040L00113684 0000003333042914R01
    Comes out as:
    040L00113684 33.33- 060514R01     

    Using ABAP try to cover the values to TEXT and the you can use the desired format
    Thanks
    Abhishek Shanbhogue

  • ABPA  code to compress table into a table of fixed-length strings

    Hi all,
    I need to compress a large, sparse table into a table of fixed-length strings in my ABAP code, and then uncompress it.  Is there a standard format or facility to do this?  I seem to remember a function that does this, but any other hints would be appreciated.
    Thank you in advance,
    Sunny

    For example, given a table like:
    Column0    Column1    Column2
    abc            C               !@#&@
                     P
    def                              $*(
    Compress it into a table consisting of one column of fixed-length strings, like:
    Column0
    0abc1C2
    !@#&@01
    P20def1
    2$*(
    ..and then uncompress it back out to the original table.
    Sunny

  • How to get a string with fixed length

    I want to implement something like movechar() of c in java. I want to return a string which has a fixed length that contains the given string and spaces for remaining length.
    Please let me know how can I implement it.
    Thanks & Regards,
    Nasrin.n

    Do you mean padding a String?
          * This method pads the string s to size n using char c to make up for missing characters.
         public static String padString(String s, int n, char c, boolean paddingLeft) {
              StringBuffer str = new StringBuffer(s);
              int strLength = str.length();
              if (n > 0 && n > strLength) {
                   for (int i = 0; i <= n; i++) {
                        if (paddingLeft) {
                             if (i < n - strLength) str.insert(0, c);
                        else {
                             if (i > strLength) str.append(c);
              return str.toString();
         }

  • How to build a fixed-length string representing an integer

    Hi,
    I would like know how can I use the API to get a String representing an int with fixed length. I mean, I would like something similar to Integer.parseInt(), but I need to set the length of that String in such a way that, for instance, if I need the String to be 5 character long, and the int is 37, the String would be 00037
    Thanks in advance and best regards,
    Miguel ?ngel

    I wrote pad() methods in my string helper that can be used for this purpose.
    In particular, you want to prepad with '0' to a length of 5:
    com.Ostermiller.StringHelper.prePad(Integer.toString(37), 5, '0');
    http://ostermiller.org/utils/StringHelper.html

  • How is the length of a string calculated in Java?  and JavaScript?

    Hi all,
    Do any of you know how the length of a string is being calculated in Java and JavaScript? For example, a regular char is just counted as 1 char, but sometimes other chars such as CR, LF, and CR LF are counted as two. I know there are differences in the way Java and JavaScript calculate the length of a string, but I can't find any sort of "rules" on those anywhere online.
    Thanks,
    Yim

    What's Unicode 4 got to do with it? 1 characteris 1
    character is 1 character.
    strings now contain (and Java chars also) is
    UTF-16 code units rather than Unicode characters
    or
    code points. Unicode characters outside the BMPare
    encoded in Java as two or more code units. So it would seem that in some cases, a single
    "character" on the screen, will require two charsto
    represent it.So... you're saying that String.length() doesn't
    account for that? That sux. I don't know. I'm just making infrerences (==WAGs) based on what DrClap said.
    I assume it would return the number of chars in the array, rather than the number of symbols (glyphs?) this translates into. But I might have it bass ackwards.

Maybe you are looking for

  • Creation of process order

    Hello, I would like to know how to create a process order, the T-code for it and i would like to know the steps involved in lnking the process order and replenishment based on the process order. Expecting an earliest response. Thanks, Maxx

  • SystemError in python bindings to XmlEventReader

    Something strange happens when I try to read the document with namespaces(or with default namespace maybe?) using XmlEventReader. Here is the sample code: #!/usr/bin/env python from dbxml import * doc="""<?xml version="1.0"?> <ls xmlns="urn:some_ns"

  • How to get a decoration like that

    i want to get some decoration like that in the picture  i'm using labview 2011 Attachments: Untitled2.png ‏12 KB

  • Mail won't sync on home network but works fine at school

    Frustrated, one day my iPad was recieving and sending mail no problem but now it won't sync with my mail accounts when I am at home, however, it works complelely fine at school or other network.  I've deleted the account and restarted the iPad, input

  • Gnome US Keyboard always appearing

    Hi, Since last upgrde to Gnome 2.28 (x86_64 version), I've been having problems with my macbook keyboard under Gnome. when I get into the keyboard settings an US layout appears, which I never set, so I delete it again to leave the spanish keyboard al