Simple string optimization question

ABAPpers,
Here is the problem description:
In a SELECT query loop, I need to build a string by concatenating all the column values for the current row. Each column is represented as a length-value pair. For example, let's say the current values are:
Column1 (type string)  : 'abc          '
Column2 (type integer) : 7792
Column3 (type string)  : 'def                    '
The resulting string must be of the form:
0003abc000477920003def...
The length is always represented by a four character value, followed by the actual value.
Note that the input columns may be of mixed types - numeric, string, date-time, etc.
Given that data is of mixed type and that the length of each string-type value is not known in advance, can someone suggest a good algorithm to build such a result? Or, is there any built-in function that already does something similar?
Thank you in advance for your help.
Pradeep

Hi,
At the bottom of this message, I have posted a program that I currently wrote. Essentially, as I know the size of each "string" type column, I use a specific function to built the string. For any non-string type column, I assume that the length can never exceed 25 characters. As I fill 255 characters in the output buffer, I have to write the output buffer to screen.
The reason I have so many functions for each string type is that I wanted to optimize concatenate operation. Had I used just one function with the large buffer, then "concatenate" statement takes additional time to fill the remaining part of the buffer with spaces.
As my experience in ABAP programming is limited to just a couple of days, I'd appreciate it if someone can suggest me a better way to deal with my problem.
Thank you in advanced for all your help. Sorry about posting such a large piece of code. I just wanted to show you the complexity that I have created for myself :-(.
Pradeep
REPORT ZMYREPORTTEST no standard page heading line-size 255.
TABLES: GLPCA.
data: GLPCAGL_SIRID like GLPCA-GL_SIRID.
data: GLPCARLDNR like GLPCA-RLDNR.
data: GLPCARRCTY like GLPCA-RRCTY.
data: GLPCARVERS like GLPCA-RVERS.
data: GLPCARYEAR like GLPCA-RYEAR.
data: GLPCAPOPER like GLPCA-POPER.
data: GLPCARBUKRS like GLPCA-RBUKRS.
data: GLPCARPRCTR like GLPCA-RPRCTR.
data: GLPCAKOKRS like GLPCA-KOKRS.
data: GLPCARACCT like GLPCA-RACCT.
data: GLPCAKSL like GLPCA-KSL.
data: GLPCACPUDT like GLPCA-CPUDT.
data: GLPCACPUTM like GLPCA-CPUTM.
data: GLPCAUSNAM like GLPCA-USNAM.
data: GLPCABUDAT like GLPCA-BUDAT.
data: GLPCAREFDOCNR like GLPCA-REFDOCNR.
data: GLPCAAWORG like GLPCA-AWORG.
data: GLPCAKOSTL like GLPCA-KOSTL.
data: GLPCAMATNR like GLPCA-MATNR.
data: GLPCALIFNR like GLPCA-LIFNR.
data: GLPCASGTXT like GLPCA-SGTXT.
data: GLPCAAUFNR like GLPCA-AUFNR.
data: data(255).
data: currentPos type i.
data: lineLen type i value 255.
data len(4).
data startIndex type i.
data charsToBeWritten type i.
data remainingRow type i.
SELECT GL_SIRID
RLDNR
RRCTY
RVERS
RYEAR
POPER
RBUKRS
RPRCTR
KOKRS
RACCT
KSL
CPUDT
CPUTM
USNAM
BUDAT
REFDOCNR
AWORG
KOSTL
MATNR
LIFNR
SGTXT
AUFNR into (GLPCAGL_SIRID,
GLPCARLDNR,
GLPCARRCTY,
GLPCARVERS,
GLPCARYEAR,
GLPCAPOPER,
GLPCARBUKRS,
GLPCARPRCTR,
GLPCAKOKRS,
GLPCARACCT,
GLPCAKSL,
GLPCACPUDT,
GLPCACPUTM,
GLPCAUSNAM,
GLPCABUDAT,
GLPCAREFDOCNR,
GLPCAAWORG,
GLPCAKOSTL,
GLPCAMATNR,
GLPCALIFNR,
GLPCASGTXT,
GLPCAAUFNR) FROM GLPCA
perform BuildFullColumnString18 using GLPCAGL_SIRID.
perform BuildFullColumnString2 using GLPCARLDNR.
perform BuildFullColumnString1 using GLPCARRCTY.
perform BuildFullColumnString3 using GLPCARVERS.
perform BuildFullColumnString4 using GLPCARYEAR.
perform BuildFullColumnString3 using GLPCAPOPER.
perform BuildFullColumnString4 using GLPCARBUKRS.
perform BuildFullColumnString10 using GLPCARPRCTR.
perform BuildFullColumnString4 using GLPCAKOKRS.
perform BuildFullColumnString10 using GLPCARACCT.
perform BuildFullColumnNonString using GLPCAKSL.
perform BuildFullColumnNonString using GLPCACPUDT.
perform BuildFullColumnNonString using GLPCACPUTM.
perform BuildFullColumnString12 using GLPCAUSNAM.
perform BuildFullColumnNonString using GLPCABUDAT.
perform BuildFullColumnString10 using GLPCAREFDOCNR.
perform BuildFullColumnString10 using GLPCAAWORG.
perform BuildFullColumnString10 using GLPCAKOSTL.
perform BuildFullColumnString18 using GLPCAMATNR.
perform BuildFullColumnString10 using GLPCALIFNR.
perform BuildFullColumnString50 using GLPCASGTXT.
perform BuildFullColumnString12 using GLPCAAUFNR.
ENDSELECT.
if currentPos > 0.
  move '' to datacurrentPos.
  write: / data.
else.
  write: / '+'.
endif.
data fullColumn25(29).
data fullColumn1(5).
Form BuildFullColumnString1 using value(currentCol). 
  len = STRLEN( currentCol ).
  concatenate len currentCol into fullColumn1.
  data startIndex type i.
  data charsToBeWritten type i.
  charsToBeWritten = STRLEN( fullColumn1 ).
  data remainingRow type i.
  do.
    remainingRow = lineLen - currentPos.
    if remainingRow > charsToBeWritten.
      move fullColumn1+startIndex(charsToBeWritten) to
        data+currentPos(charsToBeWritten).
      currentPos = currentPos + charsToBeWritten.
      exit.
    endif.
    if remainingRow EQ charsToBeWritten.
      move fullColumn1+startIndex(charsToBeWritten) to
        data+currentPos(charsToBeWritten).
      write: / data.
      currentPos = 0.
      exit.
    endif.
    move fullColumn1+startIndex(remainingRow) to
        data+currentPos(remainingRow).
    write: / data.
    startIndex = startIndex + remainingRow.
    charsToBeWritten = charsToBeWritten - remainingRow.
    currentPos = 0.
  enddo.
EndForm.
data fullColumn2(6).
Form BuildFullColumnString2 using value(currentCol). 
  len = STRLEN( currentCol ).
  concatenate len currentCol into fullColumn2.
  data startIndex type i.
  data charsToBeWritten type i.
  charsToBeWritten = STRLEN( fullColumn2 ).
  data remainingRow type i.
  do.
    remainingRow = lineLen - currentPos.
    if remainingRow > charsToBeWritten.
      move fullColumn2+startIndex(charsToBeWritten) to
        data+currentPos(charsToBeWritten).
      currentPos = currentPos + charsToBeWritten.
      exit.
    endif.
    if remainingRow EQ charsToBeWritten.
      move fullColumn2+startIndex(charsToBeWritten) to
        data+currentPos(charsToBeWritten).
      write: / data.
      currentPos = 0.
      exit.
    endif.
    move fullColumn2+startIndex(remainingRow) to
        data+currentPos(remainingRow).
    write: / data.
    startIndex = startIndex + remainingRow.
    charsToBeWritten = charsToBeWritten - remainingRow.
    currentPos = 0.
  enddo.
EndForm.
data fullColumn3(7).
Form BuildFullColumnString3 using value(currentCol). 
EndForm.
data fullColumn4(8).
Form BuildFullColumnString4 using value(currentCol). 
EndForm.
data fullColumn50(54).
Form BuildFullColumnString50 using value(currentCol). 
EndForm.
Form BuildFullColumnNonString using value(currentCol). 
  move currentCol to fullColumn25.
  condense fullColumn25.     
  len = STRLEN( fullColumn25 ).
  concatenate len fullColumn25 into fullColumn25.
  data startIndex type i.
  data charsToBeWritten type i.
  charsToBeWritten = STRLEN( fullColumn25 ).
  data remainingRow type i.
  do.
    remainingRow = lineLen - currentPos.
    if remainingRow > charsToBeWritten.
      move fullColumn25+startIndex(charsToBeWritten) to
        data+currentPos(charsToBeWritten).
      currentPos = currentPos + charsToBeWritten.
      exit.
    endif.
    if remainingRow EQ charsToBeWritten.
      move fullColumn25+startIndex(charsToBeWritten) to
        data+currentPos(charsToBeWritten).
      write: / data.
      currentPos = 0.
      exit.
    endif.
    move fullColumn25+startIndex(remainingRow) to
        data+currentPos(remainingRow).
    write: / data.
    startIndex = startIndex + remainingRow.
    charsToBeWritten = charsToBeWritten - remainingRow.
    currentPos = 0.
  enddo.
EndForm.

Similar Messages

  • A Simpler, More Direct Question About Merge Joins

    This thread is related to Merge Joins Should Be Faster and Merge Join but asks a simpler, more direct question:
    Why does merge sort join choose to sort data that is already sorted? Here are some Explain query plans to illustrate my point.
    SQL> EXPLAIN PLAN FOR
      2  SELECT * FROM spoTriples ORDER BY s;
    PLAN_TABLE_OUTPUT
    |   0 | SELECT STATEMENT |              |   998K|    35M|  5311   (1)| 00:01:04|
    |   1 |  INDEX FULL SCAN | PKSPOTRIPLES |   998K|    35M|  5311   (1)| 00:01:04|
    ---------------------------------------------------------------------------------Notice that the plan does not involve a SORT operation. This is because spoTriples is an Index-Organized Table on the primary key index of (s,p,o), which contains all of the columns in the table. This means the table is already sorted on s, which is the column in the ORDER BY clause. The optimizer is taking advantage of the fact that the table is already sorted, which it should.
    Now look at this plan:
    SQL> EXPLAIN PLAN FOR
      2  SELECT /*+ USE_MERGE(t1 t2) */ t1.s, t2.s
      3  FROM spoTriples t1, spoTriples t2
      4  WHERE t1.s = t2.s;
    Explained.
    PLAN_TABLE_OUTPUT
    |   0 | SELECT STATEMENT       |              |    11M|   297M|       | 13019 (6)| 00:02:37 |
    |   1 |  MERGE JOIN            |              |    11M|   297M|       | 13019 (6)| 00:02:37 |
    |   2 |   SORT JOIN            |              |   998K|    12M|    38M|  6389 (4)| 00:01:17 |
    |   3 |    INDEX FAST FULL SCAN| PKSPOTRIPLES |   998K|    12M|       |  1460 (3)| 00:00:18 |
    |*  4 |   SORT JOIN            |              |   998K|    12M|    38M|  6389 (4)| 00:01:17 |
    |   5 |    INDEX FAST FULL SCAN| PKSPOTRIPLES |   998K|    12M|       |  1460 (3)| 00:00:18 |
    Predicate Information (identified by operation id):
       4 - access("T1"."S"="T2"."S")
           filter("T1"."S"="T2"."S")I'm doing a self join on the column by which the table is sorted. I'm using a hint to force a merge join, but despite the data already being sorted, the optimizer insists on sorting each instance of spoTriples before doing the merge join. The sort should be unnecessary for the same reason that it is unnecessary in the case with the ORDER BY above.
    Is there anyway to make Oracle be aware of and take advantage of the fact that it doesn't have to sort this data before merge joining it?

    Licensing questions are best addressed by visiting the Oracle store, or contacting a salesrep in your area
    But I doubt you can redistribute the product if you aren't licensed yourself.
    Question 3 and 4 have obvious answers
    3: Even if you could this is illegal
    4: if tnsping is not included in the client, tnsping is not included in the client, and there will be no replacement.
    Tnsping only establishes whether a listener is running and shouldn't be called from an application
    Sybrand Bakker
    Senior Oracle DBA

  • Simple X-fi Question, Please Help

    !Simple X-fi Question, Please HelpL I've been looking for an external sound card that is similar to the 2002 Creative Extigy and think I may found it in the Creative X-Fi. I have some questions about the X-fi though. Can the X-fi:
    1. Input sound from an optical port
    2. Output that sound to 5. surround- Front, surround, center/sub
    3. Is the X-Fi stand-alone, external, and powered by a USB or a wall outlet (you do not need a computer hooked up to it)
    Basically I want to connect a TosLink optical cable from my Xbox to the X-Fi. That will deli'ver the sound to the X-Fi. Then I want that sound to go to a 5. headset that is connected to the X-fi via 5. front, surround, and center/sub wires. The X-Fi has to be stand-alone and cannot be connected to a PC to do this.
    Thank you for your help.

    The connector must match, and the connector polarity (plus and minus voltage) must match.  Sorry, I don't know if the positive voltage goes on the inside of the connector or the outside.    Any wattage of 12 or more should be adequate.
    Message Edited by toomanydonuts on 01-10-2008 01:29 AM

  • Simple Crop tool question... how do I save the crop section?

    Hi,
    I have a very simple crop tool question. I'm a photoshop girl usually... so Illustrator is new to me. When I select the crop section I want... how do I save it?... if I select another tool in the tool panel, the crop section disappears and I can't get it back when I re-select Crop tool. If I select Save as... it saves the whole document...and not just my crop section.
    Like I said, simple question...but I just don't know the secret to the Illustrator crop tool.
    Thanks!
    Yzza

    Either press the Tab key or F key.

  • Simple String Compression Functions

    Hi all !
    I need two simple String compression functions, like
    String compress(String what)
    and
    String decompress(String what)
    myString.equals(decompress(compress(myString)))
    should result in true.
    Primarily I want to encode some plain text Strings so they are not too easy to read, and compression would be a nice feature here.
    I already tried the util.zip package, but that one seems to need streams, I simply need Strings.
    Any ideas ??
    thx
    Skippy

    It does not do any compression, in fact it does
    expansion to better encrypt the string (about 50%).How does that work? You want encryption to
    decrease entropy.Why in the world do you say that, pjt33? What a very odd statement indeed. I sure hope you don't work in security, or I do hope you work in security if I'm a bad guy, or a competitor.
    Let's say you had a 6-character string you wanted to encrypt.
    Well, if you didn't increase the entropy, any 6-character plaintext string would have a 6-character encoded equivalent. And if you decreased entropy (e.g. coding the most commonly used words to shorter strings,) it gets even easier to decrypt.
    Presumably there would be no hash collisions, after all, you want this to be reversible.
    Hash collisions decrease entropy too, and, by doing so, make it easier to find a plaintext string that happens to hash to a certain value. This is a Bad Thing.
    Now, to decode this, the Bad Guy only has to consider the set of 6-character strings and their hash values. You could even precalculate all of the common dictionary words, and everything with common letters and punctuation, making decryption virtually instantaneous. Especially if you had decreased the entropy in the signal, making fewer things I had to try.
    But somebody who increased the entropy of their signal by adding random bits and increasing the encrypted size of the message to, say, 64 characters, would make it a lot harder to decrypt.
    The ideal encryption system is pure noise; pure randomized entropy. An indecipherable wall of 0 and 1 seemingly generated at random. Statistical methods can't be used against it; nothing can be deciphered from it; it's as decipherable and meaningless as radio hiss. Now that's encryption!

  • Very simple XSLT string replacing question

    Hi,
    This is a really simple question for you guys, but it took me long, and i still couldn't solve it.
    I just want to remove all spaces from a node inside an XML file.
    XML:
    <?xml version="1.0" encoding="UTF-8"?>
    <root insertedtime="2008-05-01T14:03:00.000+10:00" pkid="23421">
       <books>
          <book type='fiction'>
             <author>John Smith</author>
             <title>Book title</title>
             <year>2 0  0 8</year>
          </book>
       </books>
    </root>in the 'year' node, the value should not contain any spaces, that's the reason why i need to remove spaces using XSLT. Apart from removing space, i also need to make sure that the 'year' node has a non-empty value. Here's the XSLT:
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
        <xsl:strip-space elements="*"/>
        <xsl:template match="@*|node()">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
        </xsl:template>
        <xsl:template match="//books/book[@type='fiction']">
            <xsl:copy>
                <xsl:apply-templates select="@*"/>
                <xsl:attribute name="id">101</xsl:attribute>
                <xsl:call-template name="emptyCheck">
                    <xsl:with-param name="val" select="year"/>
                    <xsl:with-param name="type" select="@type"/>
                    <xsl:with-param name="copy" select="'true'"/>
                </xsl:call-template>
                <xsl:value-of select="translate(year, ' ', '')"/>
            </xsl:copy>
        </xsl:template>
        <!-- emptyCheck checks if a string is an empty string -->
        <xsl:template name="emptyCheck">
            <xsl:param name="val"/>
            <xsl:param name="type"/>
            <xsl:param name="copy"/>
            <xsl:if test="boolean($copy)">
                <xsl:apply-templates select="node()"/>
            </xsl:if>
            <xsl:if test="string-length($val) = 0 ">
                <exception description="Type {$type} value cannot be empty"/>
            </xsl:if>
        </xsl:template>
    </xsl:stylesheet>The 'emptyCheck' function works fine, but the space replacing is not working, this is the result after the transform:
    <?xml version="1.0" encoding="utf-8"?>
    <root insertedtime="2008-05-01T14:03:00.000+10:00" pkid="23421">
       <books>
          <book type="fiction" id="101">
             <author>John Smith</author>
             <title>Book title</title>
             <year>2 0 0 8</year>2008</book>
       </books>
    </root>The spaced year value is still there, the no-space year is added outside the 'year' tags'
    anyone can help me, your help is extremely appreciated!
    Thanks!

    You should add a template for 'year' :<xsl:template match="year">
    <year><xsl:value-of select="translate(.,' ','')"/></year>
    </xsl:template>and remove the translate call in the 'book' template.
    It would be better to add a 'priority' attribute at each template so it would be explicit which template to use because match="@*|node()" could be interpreted by another transform engine as the unique template to be used !

  • Very simple Strings Question

    Hi All:
    I am stuck with a small situation, I would appreciate if someone can help me with that. I have 2 strings:
    String 1 - "abc"
    String 2 - "I want to check if abc is in the middle"
    How can I check if the string 1 "abc" is in the middle of the string 2. I mean the String 2 does not start with "abc" and it does not end with "abc", I want to check if it is somewhere between the string.
    Thanks,
    Kunal

    int i = s2.indexOf(s1);
    if((i > 0) && ((i + s1.length()) < s2.length())) {
       // somewhere in the middle
    } else if(i == 0) {
       // start
    } else if((i + s1.length()) == s2.length()) {
       // end
    } else if(i == -1) {
       // nowhere
    }

  • Simple string question

    I want to compare two strings, suppose that:
    first string = "-Hello"
    second string = " -Hello"
    I want that both return same result.
    A lot of thanks!

    i would filter out all whitespaces first and the use the string.compare() function.
    write a open methode that allows you to filer out any char in any string and returns the filtered string. you can do so by building a while (indexOf(char)) loop and cutting out the unwanted chars with the subString() command.

  • Simple (?) JS question: use a variable in place of a string

    I'm working on a script that will take a selection and add it to the index multiple times, as a level 2 topic under different level 1 topics. Sometimes, it would be nice to edit the selection before creating the page references.
    I want to use a dialog box, which would have checkboxes for the level 1 entries, and an edit box that shows what will be the level 2 part of each reference. The edit box should start containing what was selected when the script was run.
    The ComplexUI.jsx sample script contains this on line 17:
    var myTextEditField = textEditboxes.add({editContents:"Hello World!", minWidth:180});
    I would like to use the variable into which I captured the selection in place of "Hello World!" Obviously, I'd use more than the one line, but I just pasted in the one that seems most relevant.
    I can't figure out how to do it. When I try, I get an error stating that a string was expected, but text was encountered.
    I'm sure this is truly one of the more basic JavaScript skills, but it is one I lack. Can anyone enlighten me?

    From the error message, I'd deduce that you are trying to use a direct reference to text in the document when you need the contents of the text.
    So, if you're using myText, try myText.contents.
    Dave

  • Simple java architecture question

    This should be a simple question to answer but I haven't been able to find a good answer.
    I have an application that establishes a network connection with a server and registers event listeners on that connection.
    What I want to do is find a way without a busy-wait/while loop to keep the main() thread running so that the listeners can do their job.
    Here is a sample of what I've got:
    public static void main(String[] args)
    SomeConnection conn1 = null;
    try
    conn1 = new SomeConnection("someaddress");
    TrafficManager tm = conn1.getTraffictManager();
    TrafficHandler th = tm.createTraffichandler(new MessageListener()
                        public void processMessage(Message message)
                             System.out.println("Received: " + message.toString());
         catch (Exception e)
              e.printStackTrace(System.out);
         conn1.disconnect();
    The problem is that the application doesn't stay running to respond to traffic coming across the connection.
    Any guidance would be appreciated.
    Thanks

    Well, what is the job of the MessageListener if it isn't to listen for messages? And apparently it isn't doing that because your application terminates.
    Bear in mind that I don't have any idea how any of those four classes work, or even how they are supposed to work. So let me just quote this line from the API documentation of the Thread class which says when your application will terminate:
    "All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method."
    That must be the case in your application.

  • Simple Java Coding Question

    I know this is a simple question, but I can't search for the answer to this because it involves syntax that Google and the like don't seem to search for..
    I am trying to figure out some Java code that I have found. I would like to know what:
    a[--i] and a[++j] mean.
    My first thought was that they meant to look at the position in the array one less (or more) than i (j). But that doesn't seem to be the case. A is an array of Strings, if that matters...
    Thanks for you help.

    muiajc wrote:
    I know this is a simple question, but I can't search for the answer to this because it involves syntax that Google and the like don't seem to search for..
    I am trying to figure out some Java code that I have found. I would like to know what:
    a[--i] and a[++j] mean.
    It mean increase/decrease the int i/j by 1. This is done before it gets you the value of a[]. for example if i=5 and you said a[--i] it is really a[4] and i is now equal to 4;

  • Another simple classpath problem question

    Hi All
    Yes I know, there are a lots of questions about this matter, but I couldn't found a solution to my problem.
    I have a simple program:
    public class prueba {
            public static void main(String[] args) {
                    System.out.println("Ahi va...");
    }placed in /tmp/javier/prueba.java
    After compiled, I've tried to run it from / and then problems started:
    cd /
    java /tmp/javier/prueba
    Exception in thread "main" java.lang.NoClassDefFoundError: /tmp/javier/prueba (wrong name: prueba)
    I said, ok...it could be a classpath problem...then:
    java -cp /tmp/javier/ /tmp/javier/prueba
    Exception in thread "main" java.lang.NoClassDefFoundError: /tmp/javier/prueba
    Damn, another try...
    java -cp .:/tmp/javier/ /tmp/javier/prueba
    Exception in thread "main" java.lang.NoClassDefFoundError: /tmp/javier/prueba (wrong name: prueba)
    Jesus Christ....may be the last slash....
    java -cp .:/tmp/javier /tmp/javier/prueba
    Exception in thread "main" java.lang.NoClassDefFoundError: /tmp/javier/prueba (wrong name: prueba)
    Oh...no.... may be classpath to java classes..
    java -cp .:/usr/java/j2sdk1.4.2_01/lib/jre/:/tmp/javier/ /tmp/javier/prueba
    Exception in thread "main" java.lang.NoClassDefFoundError: /tmp/javier/prueba (wrong name: prueba)
    Well, I don't know why this error happens....
    Please, could somebody help me !!!
    Thanks in advance...
    <jl>

    It's not too early to start following the Sun coding
    conventions for Java:
    http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.
    tmlHi
    thanks for your reply.
    Yes, I agree. I use conventions with my programs. But my real problem was with a real application and then I did quickly this simple code to help others to understand the problem and give a fast reply...
    Let me know if that works. (It was fine on my
    machine.) - MODYes it works fine, thanks.... and Damn...Murphys law again, the only option I didn't tried is the solution to my problem... :)
    Thanks again...

  • Classes and subclasses given as String input - question

    Hello, I am new in Java so please don't laugh at my question!!
    I have a method as the following and I am trying to store objects of the type Turtle in a vector. However the objects can also be of Turtle subclasses: ContinuousTurtle, WrappingTurtle and ReflectingTurtle. The exact class is determined by the String cls which is input by the user.
    My question is, how can I use cls in a form that I don't have to use if-else statements for all 4 cases? (Imagine if I had 30 subclasses).
    I have tried these two and similar methods so far but they return an error and Eclipse is not of much help in this case.
    Simplified methods:
    //pre:  cls matches exactly the name of a valid Turtle class/subclass
    //post: returns vector with a new turtle of type cls added to the end
    private Vector<Turtle> newturtle(Vector<Turtle> storage, String cls){
         Turtle t = new cls(...);
         storage.add(t);
         etc.
    private Vector<Turtle> newturtle(Vector<Turtle> storage, String cls){
         Turtle t = new Turtle<cls>(...);
         storage.add(t);
         etc.
    }Thanks for your help.
    p.s.: I didn't know whether to post this question here or under Generics.

    a Factory is atually very simple (100x simpler than reflection).
    example:
    class TurtleFactory
      public Turtle makeTurtle(String typeOfTurtle)
        if (typeOfTurtle.equals("lazy") { return new LazyTurtle(); }
        else if (typeOfTurtle.equals("fast") { return new FastTurtle(); }
        <etc>
    }While at first this doesn't look any better than your original problem, what we've done is made a class that is responsible for all the types of turtles. This will also benefit in case some turtles need initialization or need something passed to their constructor. You encapsulate all that knowledge in one place so you rcode doesn't become littered with it else ladders.

  • Very simple and quick question about Arrays

    Hi,
    I have the following code to produce a student grades provessing system. I have got it to store data in the array, i just cant figure out how to add the integers from the row to produce a total. Thats all I want to do create a total from the 6 marks and add a percentage.
    Any help would be greatly appreciated.
    -------------CODE BELOW----------------------
    import java.util.*;
    public class newstudent1_2
    public static void main (String[]args)
    System.out.println ("-----------------------------------------------"); //Decorative border to make the welcome message stand out
    System.out.println (" Welcome to Student Exam Mark Software 1.2"); //Simple welcome message
    System.out.println ("-----------------------------------------------");
    int [][] mark;
    int total_mark;
    int num_students;
    int num_questions = 9;
    Scanner kybd = new Scanner(System.in);
    System.out.println("How many students?");
    num_students =kybd.nextInt();
    mark = new int[num_students][num_questions] ;
    for (int i=0; i<num_students; i++)
    System.out.println("Enter the Students ID");
    String student_id;
    student_id =kybd.next();
    System.out.println("Student "+i);
    for( int j=1; j<num_questions; j++)
    System.out.println("Please enter a mark for question "+j);
    mark[i][j]=kybd.nextInt();
    System.out.print("id mark1 mark2 mark3 mark4 mark5 mark6 mark7 mark8");
    //This section prints the array data into a table
    System.out.println();
    for (int i=0; i<num_students; i++)
    for( int j=0; j<num_questions; j++)
    System.out.print(mark[i][j]+"\t"); //the \t is used to add spaces inbetween the output table
    System.out.println();
    --------------END OF CODE---------------
    Thanks.

    I had to do this same sort of thing for a school assignment but i didnt use an array.
    import java.text.DecimalFormat;
    import TurtleGraphics.KeyboardReader;
    public class grade_avg
         public static void main(String[] args)
              int grade, total = 0, count = 0;
              double avg = 0.0;
              KeyboardReader reader = new KeyboardReader();
              DecimalFormat df = new DecimalFormat("0.00");
         for (;;)
                   grade = reader.readInt("Please enter a grade: ");
              if (grade > 0)
                        total = total + grade;
                        count ++;
              if (grade == 0)
                        avg = total / count;
                        System.out.println("The average is: " + df.format(avg));
                        System.exit(0);
    }output looks like:
    Please enter a grade: 100
    Please enter a grade: 50
    Please enter a grade: 0
    The average is: 75.00

  • Write a simple string to a file.

    I have a string that is formatted with new lines that I want to write to a file as is. I have not been able to create a File Partner Link that can successfully write the content.
    The opaque approach creates an empty file.
    I have tried defining a new schema as a string, a delimited and a fixed length and the closest I have come is getting the last line written with fixed length.
    This is the input schema. I want to write the file element. The complex_child element contains values I would use to build the file name.
    <xs:complexType name="complex_parent_type">
    <xs:sequence>
    <xs:element name="complex_child" type="ns1:complex_child_type"/>
    <xs:element name="file" type="xs:string"/>
    </xs:sequence>
    </xs:complexType>
    Anybody have any success? I would think this should be a simple process. We would prefer not to use embedded Java.
    Thanks,
    Wes.

    Hi Wes,
    You could try using this schema:
    <?xml version="1.0" ?>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:nxsd="http://xmlns.oracle.com/pcbpel/nxsd"
    targetNamespace="..."
    xmlns:tns="..."
    elementFormDefault="qualified" attributeFormDefault="unqualified"
    nxsd:encoding="US-ASCII" nxsd:stream="chars"
    nxsd:version="NXSD" >
    <xsd:element name="file" type="xsd:string" nxsd:style="terminated"
                                  nxsd:terminatedBy="${eof}">
    </xsd:element>
    </xsd:schema>
    You could copy over the contents of the string that you want to write out into the element above and then use the "invoke" on a file adapter PL to write it out.
    Regards,
    Narayanan

Maybe you are looking for

  • Changing apple id on macbook pro

    Hi I initally set up my macbook pro under my moms apple id account, whenever i want to facetime and use my message it goes through her phone and not my computer. I have my own apple id and i would like to use that for facetime and messages, yet still

  • Select in PL/SQL tables ?

    Hi, I have create PL/SQL Table , i want to know how can i remove the redundancy of data as in SQL query when i used UNION ALL or DISTINCT Operators. The second Question is How can show(Retrieve query) only one element in SQL SUCH AS SELECT ID from PL

  • Webforms menu modification

    webforms menu modification Is there any way to add to or remove functionality from the menu when deploying forms? i.e. the menu that has the 'Action', 'Edit', 'Query', ..., 'Help', 'Window' drop-down menus? Or is this menu static and not changable. I

  • Oracle reports command line

    Hello, I have an NT command file with a bunch of calls to R30run32.. Almost every night the job fails to run all the commands.. but just hangs on a particular call.. with no oracle session running.. but r30run32 still running when I look at task mana

  • I could not read websites in tamil language(unicode)

    When I try to read websites in tamil language example: http://ta.wikipedia.org , i see only boxes. I use HTC Desire HD using Android 2.2 Android natively doesnt support tamil & dont have tamil font in it. I have rooted my phone and have tamil fonts c