Tokens and arrays

hello, I need help with the following. I have broken contents of file into tokens, and now I want to load those tokens into arrays and display the contents of the arrays. How do i do this?
The name of the file is testing.txt with the following three lines;
Hey your world!
beware of mortgage fraud.
Research before you buy!
my code is as follows;
import java.io.*;
import java.util.StringTokenizer;
import java.util.*;
public class Test{
     public static void main(String[] args){
          try{
               //collect a file path / name from the user
               System.out.println( " Enter the filepath for loading" );
               Scanner myScanner = new Scanner(System.in);
               String fileName = myScanner.next();
               //load the contents of that file into a bufferedreader
               FileReader myFR = new FileReader(fileName);
               BufferedReader myBR = new BufferedReader(myFR);
               String line = " ";
               StringTokenizer words;
               String word = " ";
               System.out.println("Here are the lines in the file ");
               System.out.println(" ");
               //loop through the lines of the document (which method reads lines?)
               //main loop repeats until there are no more line
               while((line = myBR.readLine())!=null)
               {System.out.println(" The line is ");
                    System.out.println(line);
                       //line = myBR.readLine();
                    System.out.println("");
                    System.out.println( " Broken like a token ");
                    System.out.println( "");
               ////break each line into tokens,
                  words = new StringTokenizer(line);
                  ////loop through the tokens, process each word in the line
                  while(words.hasMoreTokens()){
                    word = words.nextToken();
                    System.out.println(word);
               //end while
               //load each token into an array
               String wordAry [] = new String[11];
               //loop through the array and present each token to the user          
                    for(int index=0; index<13; index++){      
               System.out.println(wordAry[index]);
               System.out.println("");
          System.out.println(" The Contents of array Results " );
          }catch(FileNotFoundException e){
               System.out.println("File could not be found or opened");
          }catch(IOException e){
               System.out.println("Error reading file");
          }// end catch
     }//end main
}//end class

Well you've definitely created an array...but you never put anything in it. You have to actually put something IN the array in order to get it out later. Also, your array is size 11, meaning the indexes go from 0 to 10. But your print loop goes from 0 to 12, so you'll get an out of bounds exception.
If you don't understand array basics, read the tutorial: [http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html]

Similar Messages

  • All the xml and arrays are getting NULL Problem

    Hello guys
    I am working on a project which uses xml loading, e4x and array manipulation extensively, and it was going good but now I got stuck on a strange problem.  Whole code was fine and application was working and responding in a desired way, but then mystourisly it stopped working and started to retun NULL values to almost all the actionscript (internal) Arrays and XML varibales.
    Now Whenever i load xml file and assign the loaded values to internal xml variables, internal values get only NULL instead of data.
    Same is the situation with Arrays, I created some components in mxml, and when i passed them to arrays by reference, code gets compiled successfully, but again Array has only null values [that code was working fine too]
    I am wondering if Adobe Flex did a silenced update or something similar and it is the result of that things !
    I am using Adobe Flex 3.2 with SDK 3.3 on windows Vista Ultimate.
    Please check this attached project, Import it and see if you face the same problem
    Thanks
    Link to Problem Project
    http://isolatedperson.googlepages.com/problemXperiment.zip
    Problem Screenshot
    http://isolatedperson.googlepages.com/xmlissue.JPG

    Use HTTPService to load the data. You'll have fewer problems.
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application creationComplete="dataSvc.send();"
      xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
         <mx:Script>
              <![CDATA[
                import mx.collections.XMLListCollection;
                import mx.rpc.events.ResultEvent;
                [Bindable] private var xlc:XMLListCollection;
                   private function loadXML(evt:ResultEvent):void{
                    xlc =  new XMLListCollection([email protected] as XMLList);
              ]]>
         </mx:Script>
         <mx:HTTPService resultFormat="e4x" result="loadXML(event)" url="alirazaTree.xml" id="dataSvc"/>
         <mx:ComboBox id="cbx" dataProvider="{xlc}"/>
    </mx:Application>

  • Loops and Arrays help

    Hi,
    I'm a freshman in college and new to java. I am completely lost and really need help with a current assignment. Here are the instructions given by my teacher...
    Building on provided code:
    Loops and Arrays
    Tracking Sales
    Files Main.java and Sales.java contain a Java application that prompts for and reads in the sales for each of 5 salespeople in a company. Files Main.java and Sales.java can be found here http://www.ecst.csuchico.edu/~amk/foo/csci111/labs/lab6N/Main.java
    and here http://www.ecst.csuchico.edu/~amk/foo/csci111/labs/lab6N/Sales.java It then prints out the id and amount of sales for each salesperson and the total sales. Study the code, then compile and run the program to see how it works. Now modify the program as follows:
    1. (1 pts) Compute and print the average sale. (You can compute this directly from the total; no new loop is necessary.)
    2. (2 pts) Find and print the maximum sale. Print both the id of the salesperson with the max sale and the amount of the sale, e.g., "Salesperson 3 had the highest sale with $4500." Note that you don't necessarily need another loop for this; you can get it in the same loop where the values are read and the sum is computed.
    3. (2 pts) Do the same for the minimum sale.
    4. (6 pts) After the list, sum, average, max and min have been printed, ask the user to enter a value. Then print the id of each salesperson who exceeded that amount, and the amount of their sales. Also print the total number of salespeople whose sales exceeded the value entered.
    5. (2 pts) The salespeople are objecting to having an id of 0-no one wants that designation. Modify your program so that the ids run from 1-5 instead of 0-4. Do not modify the array-just make the information for salesperson 1 reside in array location 0, and so on.
    6. (8 pts) Instead of always reading in 5 sales amounts, allow the user to provide the number of sales people and then create an array that is just the right size. The program can then proceed as before. You should do this two ways:
    1. at the beginning ask the user (via a prompt) for the number of sales people and then create the new array
    2. you should also allow the user to input this as a program argument (which indicates a new Constructor and hence changes to both Main and Sales). You may want to see some notes.
    7. (4 pts) Create javadocs and an object model for the lab
    You should organize your code so that it is easily readable and provides appropriate methods for appropriate tasks. Generally, variables should have local (method) scope if not needed by multiple methods. If many methods need a variable, it should be an Instance Variable so you do not have to pass it around to methods.
    You must create the working application and a web page to provide the applications information (i.e., a page with links to the source code, the javadoc and an object model) to get full credit. You can use the example.html's from the last two labs to help you remember how to do this.
    I'm not asking for someone to do this assignment for me...I'm just hoping there is someone out there patient and kind enough to maybe give me a step by step of what to do or how to get started, because I am completely lost from the beginning of #1 in the instructions.
    Any help would be much appreciated! Thank you!
    Message was edited by:
    Scott_010
    Message was edited by:
    Scott_010

    First ask the person who gave this asignment as to why do you require two classes for this , you can have only the Sales.java class with main method in it . Anyways.
    Let Main.java have a main method which instanciates a public class Sales and calls a method named say readVal() in Sales class.
    In the readVal method of sales class define two arrays i.e ids and sales. Start prompting the user for inputting the id and sales and with user inputting values keep storing it in the respective arrays .. Limit this reading to just 5 i.e only 5 salesPerson.
    Once both the arrays are populated, call another method of Sales class which will be used for all computations and output passing both the arrays.
    In this new method say Compute() , read values from array and keep calculating total,average and whatever you want by adding steps in just this loop. You can do this in readval method too after reading the values but lets keep the calculation part seperate from input.
    You must create the working application and a web page to provide the applications information (i.e., a page with links to the source code, the javadoc and an object model) to get full credit. You can use the example.html's from the last two labs to help you remember how to do this. I think this is ur personal stuff , but if you want to use web page , you probably will require to use servlet to read values from the html form passed to the server.

  • Synchronizer token and JSF

    Hello,
    I am just wondering if JSF offers a synchronizer token feature in order to avoid multiple form submissions.
    Thanks in advance,
    Albert Steed.

    Here's how I've implemented a token synchronizer pattern in my web app.
    This example has a session-scope Visit object and request-scope RequestBean:
      <managed-bean>
        <description>Session bean that holds data and delegates needed by request beans.</description>
        <managed-bean-name>visit</managed-bean-name>
        <managed-bean-class>com.example.Visit</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
      </managed-bean>
      <managed-bean>
        <description>Some request bean.</description>
        <managed-bean-name>reqBean</managed-bean-name>
        <managed-bean-class>com.example.RequestBean</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
        <managed-property>
          <property-name>visit</property-name>
          <value>#{sessionScope.visit}</value>
        </managed-property>
      </managed-bean>My Visit class has the following:
        private long activeToken;
        private long receivedToken;
         * This returns the active save token.  Note that this is not the same
         * variable that is set by the setSaveToken() method.  This is so we can put a
         * tag in a JSP:<br/>
         *   <h:inputHidden value="#{visit.saveToken}" /> <br/>
         * That will retrieve the active token from Visit when the page
         * is rendered, and when the page is returned, setSaveToken() sets the
         * received token.  The tokens can then be compared to see if a save
         * should be performed.  See BaseBean.generateToken() for more details.
         * @return Returns the active save token.
        public long getSaveToken() {
            return this.activeToken;
         * Sets the received token.  Note that this method is only intended to be
         * called by a JSF EL expression such as: <br/>
         *   <h:inputHidden value="#{visit.saveToken}" /> <br/>
         * See getSaveToken() for more details on why.
         * @param received token value to set
        public void setSaveToken(long aToken) {
            this.receivedToken = aToken;
        void setReceivedToken(long aToken) {
            this.receivedToken = aToken;
        long getReceivedToken() {
            return this.receivedToken;
        void setActiveToken(long aToken) {
            this.activeToken = aToken;
        long getActiveToken() {
            return this.activeToken;
         * @return true if the active and received token are both non-zero and they match
        boolean tokensMatchAndAreNonZero() {
            return (this.activeToken != 0) && (this.receivedToken != 0) && (this.activeToken == this.receivedToken);
    . . .My backing beans extend a base class BaseBean with these methods:
         * Generates a new save token, saving it to a field in Visit. Guaranteed to not
         * generate a 0 (0 is used to denote an expired token).<br/><br/>
         * This token is used to make sure that
         * actions that modify data in a way that should not be immediately repeated.
         * Call this method prior to rendering a page that will submit the non-repeatable
         * request.  Then before saving any data, call saveTokenIsInvalid() to see if the
         * save should be executed.  If the token is valid, expire it and proceed with
         * saving.<br/>
         * The view that submits an unrepeatable request should have the tag:<br/>
         *      <h:inputHidden value="#{visit.saveToken}" /><br/>
         * in it.  Visit.getSaveToken() will set this field with the active token when the
         * page is rendered.  Visit.setSaveToken() will set a received token field, which
         * can then be compared to the active token to find out whether a save should be
         * performed.
        protected void generateSaveToken() {
            logger.debug("generateSaveToken()");
            Random random = new Random();
            long token = random.nextLong();
            while (token == 0) {
                token = random.nextLong();
            this.getVisit().setActiveToken(token);
            this.getVisit().setReceivedToken(0);
         * Checks the save token to see if it is valid.
         * @true if the save token is invalid.  It is invalid if either the received or the active
         * tokens in Visit are zero, or if the tokens do not match.
        protected boolean saveTokenIsInvalid() {
            if (logger.isDebugEnabled() ) {
                logger.debug("saveTokenIsInvalid():\nactive token: " + this.getVisit().getActiveToken() + "\nrecv'd token: " + this.getVisit().getReceivedToken() );
            boolean isValid = this.getVisit().tokensMatchAndAreNonZero();
            // return the inverse because this method is called "saveTokenIsInvalid"
            return !isValid;
         * Sets active token to zero, preventing any saves by methods that check for valid save token
         * before committing a change until generateSaveToken() is called again.
        protected void expireSaveToken() {
            logger.debug("expireSaveToken()");
            this.getVisit().setActiveToken(0);
         * Logs an info message saying that a save action was not performed because of invalid save
         * token.  Returns given String as outcome.
         * @param logger for subclass calling this method
         * @param outcome
         * @return outcome
        protected String logInvalidSaveAndReturn(Logger subclassLogger, String outcome) {
            if (subclassLogger.isInfoEnabled() ) {
                subclassLogger.info("User " + this.getVisit().getUsername() + " submitted a save request that was not " +
                        "processed because the save token was not valid.  Returning outcome: '" + outcome + "'.");
            return outcome;
        // Used by JSF managed bean creation facility
        public Visit getVisit() {
            return this.visit;
        // Used by JSF managed bean creation facility
        public void setVisit(Visit visit) {
            this.visit = visit;
    . . .Any method that sets up a view containing a form I only want submitted once generates a token:
           this.generateSaveToken();And the token gets embedded in the HTML form with the tag:
    <h:inputHidden value="#{visit.saveToken}" />An action method in RequestBean would then use the token to prevent multiple identical saves as follows:
        public String someActionMethod() {
            // prevent identical requests from being processed
            String normalOutcome = Constants.NavOutcome.OK;
            if (this.saveTokenIsInvalid() ) {
                return this.logInvalidSaveAndReturn(logger, normalOutcome);
            this.expireSaveToken();
            logger.debug("save token is valid.  attempting to save....");
            try {
                  // invoke some business logic here
            } catch (MyException exc) {
                  // important: if you are returning the user to the same form view with an error message,
                  // and want to be able to process subsequent form submissions, then the token
                  // needs to be regenerated
                  this.generateSaveToken();
                  return null;
    . . .It has worked great so far. The only problems I've had are when I forget to generate or expire a token, or I forget to embed it in my form.
    I also had a problem where I expired the token after my business logic completed, and my business logic took about 30-60 seconds to process--if the user clicks on the submit button several times while waiting for the page to return, the backing bean method still sees a valid token and processes the request. This was solved by simply expiring the token prior to invoking the business logic (as shown in the above example).
    HTH,
    Scott

  • Challeging Traversal of Vector and Array

    Hi there ! I would like to render the values of this Vector and Array . How do I print it out to the browser ?
    try
    ResultSet rset = stmt.executeQuery(myQuery);
    System.out.println(" Finish Execute Query !!! ");
    /* Array Contruction */
    int numColumns = rset.getMetaData().getColumnCount();
    while (rset.next())
    aRow = new String[numColumns];
    for (int i=0; i < numColumns; i++){
    aRow[i] = rset.getString(i+1);
    allRows.addElement(aRow);
    return allRows;
    }

    Hi there !
    Thanks for your help but I managed to get it working. For references purposes, I`ll post it here.
    My problem now is this :-
    How can I issue another SQL statement and store the results in the same array?
    Pls note . One Sql per table so, that`s the issue ?
    Can someone help with a followup code ?
    try
    ResultSet rset = stmt.executeQuery(myQuery);
    System.out.println(" Finish Execute Query !!! ");
    /* Array Contruction */
    int numColumns = rset.getMetaData().getColumnCount();
    while(rset.next())
    // for every record instance aRow
    aRow = new String[numColumns];
    // store in aRow the values of the record
    for(int i=0;i<numColumns;i++)
    aRow[i] = rset.getString(i+1);
    //When aRow is full store it in the vector
    allRows.addElement(aRow);
    // when the rset finished print all the Vector
    for(int i=0;i<allRows.size();i++)
    // get returns a String[]
    String[] tmpRow = (String[])allRows.get(i);
    for(int j=0;j<tmpRow.length;j++)
    out.print(tmpRow[j]+" ");
    out.println("");
    }

  • Since I upgraded to Lion, my RSA securid token and Cisco VPN client doesn't work any longer. Anyone have suggestions on how to fix that?

    Since upgrading to Lion, I can no longer use VPN because my RSA securid token and CIsco VPN Client won't load. Any suggestioins out there?

    .

  • NXT Flatten to String Not Working with Clusters and Arrays

    Hello,
    My name is Joshua and I am from the FIRST Tech Challenge Team 4318, Green Machine. We are trying to write a program that will write to a configuration file and read it back. The idea is that we will be able to write to a config file from our computer that will be read by our autonomous program when it runs. This will define what the autonomous program does.
    The easiest way to do this seems to be flattening a data structure to a string, saving it to a file, and then reading back and unflattening it. The issue is that the flatten to string and unflatten from string VIs don't seem to work with arrays and clusters on the NXT. It does work when running on the computer. We've tried arrays, clusters, clusters in arrays and arrays in clusters, none seem to work. Thinking it was something to do with reading the string from a file, we tried bypassing the file functionality, still not working. It does work with basic data types though, such as strings and numbers.
    No error is thrown from what we can tell. All you get is a blank data structure out of the unflatten VI.
    The program attached is a test program I've been working on to get this functionality to work. It will display the hex content of what is going into the file, coming out of the file, and then the resulting data from the unflatten string, as well as any errors that have been thrown. The data type we are using simulates what we would like to store. There is also a file length in and out counter. The out file is a little larger because the NXT write file VI adds a new line character on to the end (thus the use of the strip white space VI). This character was corrupting even basic data types saved to file.
    I would like to know if there is a problem with what we are doing, or if it is simply not possible to flatten arrays on the NXT. Please ask if you have any questions about the code. Thank you in advanced!
    Joshua
    Attachments:
    ReadableTest.vi ‏20 KB

    Hi jfireball,
    This is a very interesting situation. Take a look at what kbbersch said. I also urge you to post in the FTC Forums. You posted your question to the general LabVIEW forums, but by posting to the FTC Forums, you will have access to others that are using the NXT hardware.
    David B.
    Applications Engineer
    National Instruments

  • Strange behaviour of "And array Elements"

    If u connect an empty boolean array to "And Array Elements" function, The output is "True" !. Is this correct?. Is there something wrong ?. Please Help.

    Hi J.A.C
    This is correct.This is an explanation I've found: "This behavior is intentiional, and stems from elementary Boolean logic. The Boolean algebra primitives are analogous to numeric operations are integers. Just as the identity element for addition is 0, and for multiplication, 1; the identity for Boolean OR is FALSE, and for AND, TRUE. For example, x^0 == 1; that is, x times itself zero times is by definition 1. For the same reason boolean x ANDed with itself zero times is TRUE."
    If this is not acceptable for your application, then just use the "Array Size" VI first to check if you've an empty Array (Array size=0) and then you can pass or not the array to the "And Array Elements" function.
    Hope this helps.
    Luca
    Regards,
    Luca

  • Problems launching Object Manager and Array Manager in SSGD 4.20.983

    Hi,
    I have just installed SSGD 4.20.983 in a server which is running Solaris 10. The language of this server is Spanish.
    When I access to the webtop, I 'm not be able to launch the applications Object Manager and Array Manager.
    When I try to launch them, in the details box appears "Contrase�a" and them the timeout expires. Contrase�a is the same that password in Spanish.
    Anyone can help me?
    Regards,
    Diego

    Do you have any logfiles which look like : execpePID_error.log?
    These files should contain more information.
    Also take a look at the following section of the Administration Guide: [http://docs.sun.com/source/820-6689/chapter4.html#d0e21816]
    Especially the part '+Increasing the Log Output+'
    - Remold

  • Token and smart card reader are not detected on Mavericks if not plugged on a USB port during system boot

    Well, both token and smart card reader are not detected on OS X 10.9 if not plugged on a USB port during system boot. So, if I am already working within the system and need to use my certificates I have to plug the token or smart card reader on a USB port and restart Mavericks.
    Token is a GD Starsign and Smart Card Reader is a SCR3310 v2.
    Thoughts?

    SCS is a very good app, since I've read that Apple has discontinued support for PC/SC interfaces after the release of Mountain Lion.
    (My previous installation was a Mavericks upgrade from Lion)
    However, I don't know what and how to debug using Smart Card Services. Do you know any commands to use?
    Apparently, the SC reader reports no issues: the LED is blinking blue when no smart card is present and becomes fixed blue when a smart card is inserted – according to the manuals, this shows that there is correct communication between the OS and the CCID reader.
    I don't know what to do; I'm beginning to hypothesize it's a digital signer issue. In fact, my smart card only supports one application called File Protector (by Actalis) to officially sign digital documents. This application seems to have major difficulties in identifying the miniLector EVO.
    The generic and ambiguous internal error comes when I try to manually identify the peripheral.
    Athena CNS is one of the Italian smart cards and is automatically recognized and configured (so it's correct – no doubts about this), while "ACS ACR 38U-CCID 00 00" seems to be the real name of the miniLector.
    (I'm assuming this because System Information also returns that the real manufacturer is ACS... bit4id is a re-brander)
    However, when I click on it and then tap OK, it returns internal error.
    As first attempt, I would try to completely erase&clean File Protector files to try a reinstall. Then, if this still doesn't work, I'd debug using the terminal.
    So:
    - Do you know any applications to 100% clean files created by an installer?
    - Do you have in mind any solutions that I might have forgotten?
    Thanks in advance from an OS X fan!

  • WHAT are tokens and how it is issued and how it is viewed and solved by who

    WHAT are tokens and how it is issued and how it is viewed and solved by who
    points will be awarded

    Hi Jagrut,
    If you are talking of support token then,
    TOKENs are nothing but the issues faced in the actual live system(Production).
    So the end user who is facing will raise it, it will be assigned to the production support team and they will solve it.
    Regards,
    Atish

  • Performance of System.arraycopy and Arrays.fill

    I have some code where I call a function about 1,000,000 times. That function has to allocate a small array (around 15 elements). It would be much cheaper if the client could just allocate the array one single time outside of the function.
    Unfortunately, the function requires the array to have all of its elements set to null. With C++, I would be able to memset the contents of the array to null. In Java, the only methods I have available to me are System.arraycopy() and Arrays.fill().
    Apparently, Arrays.fill() is just a brain-dead loop. It costs more for Arrays.fill() to set the elements to null than it does to allocate a new array. (I'm ignoring possible garbage collection overhead).
    System.arraycopy is a native call (that apparently uses memcpy). Even with the JNI overhead, System.arraycopy runs faster than Arrays.fill(). Unfortunately, it's still slower to call System.arraycopy() than it is to just allocate a new array.
    So, the crux of the problem is that the heap allocations are too slow, and the existing means for bulk setting the elements of an array are even slower. Why doesn't the virtual machine have explicit support for both System.arraycopy() and Arrays.fill() so that they are performed with ultra-efficient memsets and memcpys and sans the method call and JNI overhead? I.E. something along the lines of two new JVM instructions - aarraycpy/aarrayset (and all of their primitive brethern).
    God bless,
    -Toby Reyelts

    A newly allocated array begins its life with null in its elements. There is no need to fill it with null.
    As Michael already stated, I'm not redundantly resetting all of the elements to null. Here's some code that demonstrates my point. You'll have to replace my PerfTimer with your own high performance timer. (i.e. sun.misc.Perf or whatever) Also note that the reason I'm only allocating half the array size in allocTest is to more accurately model my problem. The size of the array I need to allocate is variable. If I allocate the array outside of the function, I'll have to allocate it at a maximum. If I allocate inside the function, I can allocate it at exactly the right size.import java.util.*;
    public class AllocTest {
      private static final int count = 100000;
      public static void main( String[] args ) {
        for ( int i = 0; i < 10; ++i ) {
          allocTest();
        double allocStartTime = PerfTimer.time();
        allocTest();
        double allocTime = PerfTimer.time() - allocStartTime;
        for ( int i = 0; i < 10; ++i ) {
          copyTest();
        double copyStartTime = PerfTimer.time();
        copyTest();
        double copyTime = PerfTimer.time() - copyStartTime;
        for ( int i = 0; i < 10; ++i ) {
          fillTest();
        double fillStartTime = PerfTimer.time();
        fillTest();
        double fillTime = PerfTimer.time() - fillStartTime;
        System.out.println( "AllocTime (ms): " + allocTime / PerfTimer.freq() * 1000 );
        System.out.println( "CopyTime (ms): " + copyTime / PerfTimer.freq() * 1000 );
        System.out.println( "FillTime (ms): " + fillTime / PerfTimer.freq() * 1000 );
      private static void allocTest() {
        for ( int i = 0; i < count; ++i ) {
          Object[] objects = new Object[ 8 ];
      private static void copyTest() {
        Object[] objects = new Object[ 15 ];
        Object[] emptyArray = new Object[ 15 ];
        for ( int i = 0; i < count; ++i ) {
          System.arraycopy( emptyArray, 0, objects, 0, emptyArray.length );
      private static void fillTest() {
        Object[] objects = new Object[ 15 ];
        for ( int i = 0; i < count; ++i ) {
          Arrays.fill( objects, null );
    }I getH:\>java -cp . AllocTest
    AllocTime (ms): 9.749283777686829
    CopyTime (ms): 13.276827082771694
    FillTime (ms): 16.581995756443906So, to restate my point, all of these times are too slow just to perform a reset of all of the elements of an array. Since AllocTime actually represents dynamic heap allocation its number is good for what it does, but it's far too slow for simply resetting the elements of the array.
    CopyTime is far too slow for what it does. It should be much faster, because it should essentially resolve to an inline memmove. The reason it is so slow is because there is a lot of call overhead to get to the function that does the actual copy, and that function ends up not being an optimized memmove. Even so, one on one, System.arraycopy() still beats heap allocation. (Not reflected directly in the times above, but if you rerun the test with equal array sizes, CopyTime will be lower than AllocTime).
    FillTime is unbelievably slow, because it is a simple Java loop. FillTime should be the fastest, because it is the simplest operation and should resolve to an inline memset. Fills should run in single-digit nanosecond times.
    God bless,
    -Toby Reyelts

  • Append variable and array items after a record array search

    I would like to update a variable and array item after a record array search, and wanted to know what would be the best way of carrying it out in Javascript.
    In this case, if a match is found between the variable and area item, then the postcode item should be appended to the variable.
    The same needs to be done for the array items, but I reckon that a for loop would work best in this scenario, as each individual item would need to be accessed somehow.
    Btw due to the nature of my program, there will always be a match. Furthermore, I need to be able to distinguish between the singleAddress and multipleAddresses variables.
    Hopefully this code explains things better:
    // before search
    var singleAddress = "Mount Farm";
    var multipleAddresses = ["Elfield Park", "Far Bletchley", "Medbourne", "Brickfields"];
    // this is the record which the search needs to be run against
    plot = [{
    postcode: "MK1",
    area: "Denbigh, Mount Farm",
    postcode: "MK2",
    area: "Brickfields, Central Bletchley, Fenny Stratford, Water Eaton"
    postcode: "MK3",
    area: "Church Green, Far Bletchley, Old Bletchley, West Bletchley",
    postcode: "MK4",
    area: "Emerson Valley, Furzton, Kingsmead, Shenley Brook End, Snelshall West, Tattenhoe, Tattenhoe Park, Westcroft, Whaddon, Woodhill",
    postcode: "MK5",
    area: "Crownhill, Elfield Park, Grange Farm, Oakhill, Knowlhill, Loughton, Medbourne, Shenley Brook End, Shenley Church End, Shenley Lodge, Shenley Wood",
    // after search is run then:
    // var singleAddress = "Mount Farm, MK1"
    // var multipleAddresses = ["Elfield Park, MK5", "Far Bletchley, MK3", "Medbourne, MK5", "Brickfields, MK2"]
    Fiddle here

    I would like to update a variable and array item after a record array search, and wanted to know what would be the best way of carrying it out in Javascript.
    In this case, if a match is found between the variable and area item, then the postcode item should be appended to the variable.
    The same needs to be done for the array items, but I reckon that a for loop would work best in this scenario, as each individual item would need to be accessed somehow.
    Btw due to the nature of my program, there will always be a match. Furthermore, I need to be able to distinguish between the singleAddress and multipleAddresses variables.
    Hopefully this code explains things better:
    // before search
    var singleAddress = "Mount Farm";
    var multipleAddresses = ["Elfield Park", "Far Bletchley", "Medbourne", "Brickfields"];
    // this is the record which the search needs to be run against
    plot = [{
    postcode: "MK1",
    area: "Denbigh, Mount Farm",
    postcode: "MK2",
    area: "Brickfields, Central Bletchley, Fenny Stratford, Water Eaton"
    postcode: "MK3",
    area: "Church Green, Far Bletchley, Old Bletchley, West Bletchley",
    postcode: "MK4",
    area: "Emerson Valley, Furzton, Kingsmead, Shenley Brook End, Snelshall West, Tattenhoe, Tattenhoe Park, Westcroft, Whaddon, Woodhill",
    postcode: "MK5",
    area: "Crownhill, Elfield Park, Grange Farm, Oakhill, Knowlhill, Loughton, Medbourne, Shenley Brook End, Shenley Church End, Shenley Lodge, Shenley Wood",
    // after search is run then:
    // var singleAddress = "Mount Farm, MK1"
    // var multipleAddresses = ["Elfield Park, MK5", "Far Bletchley, MK3", "Medbourne, MK5", "Brickfields, MK2"]
    Fiddle here

  • How to split a string into tokens and iterate through the tokens

    Guys,
    I want to split a string like 'Value1#Value2' using the delimiter #.
    I want the tokens to be populated in a array-like (or any other convenient structure) so that I can iterate through them in a stored procedure. (and not just print them out)
    I got a function on this link,
    http://www.orafaq.com/forum/t/11692/0/
    which returns a VARRAY. Can anybody help me how to iterate over the VARRAY, or suggest a different alternative to the split please ?
    Thanks.

    RTFM: http://download-uk.oracle.com/docs/cd/B19306_01/appdev.102/b14261/collections.htm#sthref1146
    or
    http://www.oracle-base.com/articles/8i/Collections8i.php

  • Loops and arrays

    Hi
    I'm trying to write a loop that does the following :-
    Takes an array of index values that applies to a string adds one to the value of the index and then returns the character in this position.
    There are only four types of character within the string so I have tried to solve it with the following code:-
    for (int i=0; i < indexa.length; i++)
        if(genome.charAt(indexa[i] + 1) == 'a')
            indexia[i] += indexa;
    else if(genome.charAt(indexa[i] + 1) == 'c')
    indexic[i] += indexa[i];
    else if(genome.charAt(indexa[i] + 1) == 'g')
    indexig[i] += indexa[i];
    else if (genome.charAt(indexa[i] + 1) == 't')
    indexit[i] += indexa[i];
    I'm trying it this way but it does'nt seem to work - I've only succeeded in confusing myself - any tips would be much appreciated

    Sorry, I should have explained it better.
    The situation I've got is something like this:-
    I've got a string that looks something like this
    'aactgctcct'
    next - I've got four different arrays, each corresponding to the index of each character a, c, t and g
    so they look something like this
    indexa = {0,1}
    indexc = {2,5,7,8}
    indext = {3,6,9}
    indexg = {4}
    I am presently stuck at the next part - for which I have to return the character that is to the immediate right of the index value in the string that was analysed initially.
    e.g. for indexa ;
    0 = a
    1 = c
    for indexc;
    2 = t
    5 = t
    7 = c
    8 = t
    etc
    I don't know if this makes my predicament any clearer - I'm a genetics student this java is very new to me - I'm kinda muddling through but this bit has got me stumped !!!

Maybe you are looking for

  • How can I purchase an app already installed by another user?

    We're using MacBooks in our business and I'm the new IT guy there. Basically I've discovered that due to lots of disregard by my predecessor (who is now my boss...>_>), people have apps installed on their computers that they don't "own" due to the fa

  • Recurring Journal reducing balance

    Currently using Oracle 11i I would like to use the automatic recurring journal feature but i am unsure which one i should use! I currently have an open income balance of £30000 in period 1 my aim is to have a recurring journal that reduces this showi

  • How to insert the new row after current row in RowIterator - Steve Muench

    Hi, Our client wants the new row to be added after current row on the front end instead of before current row. we were using "new JUActionBinding(this,iterBinding,JUActionBinding.ACTION_CREATE_INSERT_ROW);" this code inserts the new row after current

  • Photomatix Pro HDR Plug-in Updated with additional Lightroom Functinality

    04-Feb 2009 Update log Updated in v3.1.3 - Tighter integration with Lightroom. HDR options are now set from the Lightroom plug-in and the processed image can be automatically re-imported into the Lightroom library. - Bug fixed: Processing files in Ca

  • Best way to achieve SSo

    We are in the middle of a new ECC 6/CRM 7 implementation and would like to know the best way to accomplish SSO in our environment so that both the regular SAP GUI and the NWBC client can benefit from single sign on. We currently have two separate AD