How do I read in strings in alphabetical order nto an array?

I've been trying this for awhile now, and I do remember seeing it in a book awhile back, but can't remember how, but I've been doing it from scratch, and it's getting long. I know the basic concept - read in the first thing to the array, after that check to see if new if smaller or bigger than last, if smaller, move it forward until the one in front(below) it is smaller, or if it hits zero. But I can't get the code very short at all... (pretty long so far and only partially working..)
Does anyone remmeber how to do this?

here's what I have so far:
     int findSpot(Person key)//make to just check to see if one before is smaller, if yes, -1, if no, just add to end
          int pos=0;
          Person tempPerson;
          Person tempPerson2;
     temp = new Person[MAX_ENTRIES];
          for( int index=0;index<count;index++)
               temp[index]=phones[index];
               System.out.println(temp[index]+ "and the index value is: " + index);
          /*need to have this read in where ever it is needed temp[count]=key;*/
          for( int index=1;index<=count;index++)
               pos=index;
               if((temp[pos-1].getName().compareTo(key.getName()))>0)
                    while(pos>0)
                         tempPerson2=temp[index];
                         System.out.println("PERSON2 = " + tempPerson2);
                         //System.out.println("IN WHILE!!!!!\nPOS = "+ pos);
                         tempPerson=temp[pos-1];
                         System.out.println(tempPerson.getName() + "(temp) is now assigned the value of " + temp[pos-1].getName()+ (pos-1));
                         System.out.println("\n\n temp[pos-1] = " +(pos-1) + temp[pos-1] + "\n\n");
                         System.out.println(temp[pos-1].getName()+ (pos-1) + " is assigned the value of (key)" + key.getName());
                         temp[pos-1]=key;
                         /*System.out.println(temp[pos] + ""+(pos) + "is assigned the value of (temp)" + tempPerson.getName());
                         System.out.println("\nshould be tom" + tempPerson2 + "\n");
                         //tempPerson2= tempPerson;
                         temp[pos]=tempPerson; //oh no! (vital
                         //now need to switch the su
                         while(pos>1)
                              //tempPerson2=temp[pos-1];
                              //System.out.println(tempPerson2.getName()+ (pos-1) + "(temp2) is assigned the value of " + temp[pos-1].getName()+ (pos-1));
                              System.out.println(temp[pos-1].getName() + ""+(pos-1) + "is assigned the value of (temp)" + tempPerson.getName());
                              temp[pos-1]=tempPerson;
                              System.out.println(temp[pos].getName() + ""+(pos) + "is assigned the value of (temp2)" + tempPerson2.getName());
                              temp[pos]=tempPerson2;//needs to be assigned 'tom'
                              pos--;
                         pos--;
               //else
               //temp[index]=key;
          count++;
          for( int index=0;index<count;index++)
               System.out.println("temp array = " + temp[index]);
               phones[index]=temp[index];
               return pos;
     }

Similar Messages

  • How can I put a list in alphabetic order?

    How can I put a list in alphabetic order?

    If you don't mind putting the list in a Table, you can use the table tools to sort the rows into alphabetic order. If you don't like the idea of a table in your document and you don't want to go through converting your text to a table and back again, you can download, and install, and setup, Devon WordService, a free third party app that provides sorting and many other useful functions.
    Jerry

  • How can i read a string with nextToken() of StreamTokenizer

    I need for my class paper to read a string from a file and i used the StreamTokenizer's method nextToken but i can not read a string with it. my code is:
    StreamTokenizer st = new StreamTokenizer(the code that gets the input from the file)
    String line;
    while ((line !=br.readLine()) != null) {
    String surname = (st.nextToken()).trim();
    but it gets me some error of:
    int can not be dereferenced
    what should I do to get the string i need?

    Look at the API for java.io.StreamTokenizer. In particular, look at the return type for nextToken().
    Good luck.

  • How do i put my songs in alphabetical order on my mac

    I've been downloading a couple songs onto my macbook air and they ar going into random order, how can i make it so that my songs are in alphabetical order?

    Are you asking about iTunes?
    In List view, click on the Name column header. In other views, there's a small Sort button in the upper-right corner of the window.

  • How to iterate through a treemap in alphabetical order

    This is with a servlet. I will have a button for next and previous. When next is pressed, I go to the next record in alphabetical order.
    I know how to use a comparator and set it up. I also know how to use an iterator with 'hasNext' function. The problem is that the servlet(or jsp, etc...) will display this to the web. Then a doPost will get called and I have to go to the 'next' or previous record from the last time the form was called.
    I don't care about concurrency yet(let me get this part down first). How do i 'track' where I was last and then go to the next record. Or is there an easier way that a treemap. I don't care about performance.

    I'm assuming you want to sort on keys, not values, since that's what SortedMaps do.
    Let's say you're using elements of class C as the keys in the map. Either have C implement Comparable, or create a Comparator that compares to C instances.
    Whether you go the Comparable or Comparator route, the body of the compare or compareTo method will be almost the same. You'll just compare whatever fields are relevant on this/obj (Comparable) or obj1/obj2 (Comparator).
    The only other difference is it's more important for Comparable's compareTo to be compatible with equals, which means you have to override equals and hashCode. You don't have to do so for Comparator, but it can make some subtle issues a bit cleaner.
    Then you could do something like the following: for (Iterator iter = <something>.iterator(); iter.hasNext();) {
        <SomeClass>sc = iter.next();
        // process this element
    } where <something> can be keySet() or entrySet(). Maybe even values(). I think values() will give the sorted order for a SortedMap, but not 100% sure.Check the docs. <SomeClass> will either be the class or the keys (for keySet()), Map.Entry (for entrySet()) or the class of the values (for values()).
    You might want to check out this tutorial, if you haven't already.
    http://java.sun.com/docs/books/tutorial/collections/

  • How do I put my bookmarks in alphabetical order? I can use the sort by function in the organize bookmarks tab but it does not save.

    When I open the bookmark tab my bookmarks are sorted in random order. I want to open the bookmark tab and have them in alphabetical order. How do I set this as the default for bookmarks?

    See http://kb.mozillazine.org/Sorting_and_rearranging_bookmarks_-_Firefox
    SortPlaces: https://addons.mozilla.org/firefox/addon/9275

  • How do I get my 'list' in alphabetical order in PAGES

    I created a document in pages and I would like to create my list in alphabetical order,   but I can't figure it out!

    No version of Pages has an inherent sort alphabetical feature. You can put your list in table and sort the column, or you can download the free WordService tool from the OS X App Store. It contains a collection of service items including Sort Lines Ascending, that will sort a selected Pages list in place. I use it.
    WordService will get installed directly from the App Store. You only need to visit the following System Preferences panel, and as you can see from the screen shot, click the services you want enabled. This is in System Preferences ▸ Keyboard. Once your list (ending in a hard return) is selected, visit Pages ▸ Services ▸ Sort Lines Ascending. If you want to read about the individual services provided with WordService, double-click on /Applications/WordService, and choose Help. This will open Preview with a discussion of the various services.

  • How can i read XML string in a loop???

    i changed xml file reader to xml string reader by
    looking around this and other forums.
    here is the code.
    public class XMLTester2 {
        public static void main(String[] args) {
            String s = "<firsttag><secondtag>123</secondtag></firsttag>";
            java.io.Reader reader = new java.io.StringReader(s);
            org.xml.sax.InputSource source = new org.xml.sax.InputSource(reader);
            org.w3c.dom.Document doc = null;
            javax.xml.parsers.DocumentBuilderFactory fact = javax.xml.parsers.DocumentBuilderFactory.newInstance();
            try {
                javax.xml.parsers.DocumentBuilder builder = fact.newDocumentBuilder();
                doc = builder.parse(source);
            } catch (javax.xml.parsers.ParserConfigurationException pce) {
            } catch (org.xml.sax.SAXException se) {
            } catch (java.io.IOException ioe) {
            } finally {
                try {
                    reader.close();
                } catch (java.io.IOException ignored) {
    }i put this stuff into a loop, but i always ends up
    having new in the loop.
                String inputLine = "Start";
                // define what's needed for XML messages
                Reader reader = new StringReader(inputLine);
                InputSource source = new InputSource(reader);
                Document doc = null;
                DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = null;
                Node xmlNode = null;
                try {
                    builder = fact.newDocumentBuilder();
                } catch (ParserConfigurationException pce) {
                // -->
                while ( (inputLine = in.readLine()) != null) {
                    System.out.println("readLine() : {" + inputLine + "}");
                    reader = new StringReader(inputLine);
                    source.setCharacterStream(reader);
                    try {
                        doc = builder.parse(source);
                    } catch (SAXException se) {
                        System.out.println("SAXException : " + se);
                        System.out.println("SAXException source : " + source.toString() );
                        se.printStackTrace();
                    } catch (IOException ioe) {
                        System.out.println("IOException : " + ioe);
                    } finally {
                        try {
                            reader.close();
                        } catch (IOException ignored) {
                    reader = null;i know putting new in the loop is VERY bad.
    i gotto get ride of this new from the loop.
    can anyone help me?

    i know putting new in the loop is VERY bad.
    i gotto get ride of this new from the loop.Don't design your application based on one-liners you heard somewhere. Do some timings to see if it matters. My guess would be that parsing an XML file would take a fair bit longer than creating a StringReader object. And you do need a new StringReader each time, they aren't reusable, so the alternatives are not obvious. And don't accept my guess about the timings, check it for yourself.

  • How Do I read a String as an XML and reply?

    Hello there to everyone reading my Post !
    I am entering a total new subject in my learning about Java Programming, where I will need to interact with a server, I was wondering If somebody could help me with a Question I have; here it is:
    A server provided me a Socket, (and that is of course an IP address and a Port), And I am supposed to connect to that server using a Java program that connects to servers using a Socket class, then I am supposed to send a String representing a valid XML, and then the server replies me With another String representing a valid XML which I am supposed to store in a String type.
    Is this exact write/read operation possible? If so, could someone please give me some code to solve this problem?
    PD: The server Does this operation only: recieve/send Strings. as its called transactional switch.
    Sorry If I have put this Query in the Wrong Forum, I have put it in Networking also, just in case. Excuse me for any inconveniences.
    Message was edited by:
    BCE_Jose

    I am supposed to send a String representing a valid XML.what do you mean? do you want to send value that you get from XML doc or what? cos i don't understand about "String representing a valid XML". is it XML document exists or not? can you give us more detail about what you asking for.

  • How to get password as string back from encrypted password byte array.

    Hi All,
    I am storing encrypted password and enc key in the database.(Code included encryptPassword method for encryption and validatePassword method for validating of password). Problem is that for some reason i need to show user's password to the user as a string as he/she entered. But i am not able to convert the encrypted password from D/B to original String.
    Tell me if any body know how to get the string password back from the encrypted password byte array after seeing my existing encryption code.
    //********* Code
    private Vector encryptPassword(byte[] arrPwd)
    try
    // parameter arrPwd is the password as entered by the user and to be encrypted.
    byte[] encPwd = null;
    byte[] key = null;
    /* Generate a key pair */
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN");
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
    keyGen.initialize(1024, random);
    KeyPair pair = keyGen.generateKeyPair();
    PrivateKey priv = pair.getPrivate();
    PublicKey pub = pair.getPublic();
    /* Create a Signature object and initialize it with the private key */
    Signature dsa = Signature.getInstance("SHA1withDSA", "SUN");
    dsa.initSign(priv);
    /* Update and sign the data */
    dsa.update(arrPwd, 0, 12);
    /* Now that all the data to be signed has been read in, generate a signature for it */
    encPwd = dsa.sign();
    /* Now realSig has the signed password*/
    key = pub.getEncoded();
    Vector vtrPwd = new Vector(2);
    vtrPwd.add(encPwd);
    vtrPwd.add(key);
    return vtrPwd;
    catch (Exception e)
    private boolean validatePassword(byte[] arrPwd,byte[] encPwd,byte[] key) throws RemoteException
    try
    // arrPwd is the byte array of password entered by user.
    // encPwd is the encrypted password retreived from D/B
    // key is the array of key through which the password was encrypted and stored.
    X509EncodedKeySpec KeySpec = new X509EncodedKeySpec(key);
    KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
    PublicKey pubKey = keyFactory.generatePublic(KeySpec);
    /* Encrypt the user-entered password using the key*/
    Signature sig = Signature.getInstance("SHA1withDSA", "SUN");
    sig.initVerify(pubKey);
    /* Update and sign the password*/
    sig.update(arrPwd, 0, 12);
    return sig.verify(encPwd);
    catch (Exception e)
    Help upto any extent would be appreciated.
    Thanx
    Moti Singh

    Hi All,
    I am storing encrypted password and enc key in the
    database.(Code included encryptPassword method for
    encryption and validatePassword method for validating
    of password). Problem is that for some reason i need
    to show user's password to the user as a string as
    he/she entered. But i am not able to convert the
    encrypted password from D/B to original String.No, you are not encrypting the password in your code, you are merely signing it.
    Tell me if any body know how to get the string
    password back from the encrypted password byte array
    after seeing my existing encryption code.It is impossible to retrieve the original text out of a signature.
    You should read up on some encryption basics in order to understand the difference between signing and encrypting. Then you can find examples of how to encrypt something here: http://java.sun.com/j2se/1.4/docs/guide/security/jce/JCERefGuide.html.
    Actually there is one class specifically for keeping keys secure, KeyStore http://java.sun.com/j2se/1.4/docs/api/java/security/KeyStore.html
    - Daniel

  • Help:How to get a java String value from a C char array?

    Hi,everyone,could you help me?
    the following is a C struct that i want to recieve a short message:
    struct MO_msg{
    unsigned long long msgID;          //Message ID
    char      dest_id[21]; //Destination Mobile Phone Number
    char      service_id[10];     //
    Now I want to put the "dest_id " value of this struct into a Java String variable.But I dont know how to implement it!
    The following is a block of source code that i implement this functions.But it cant get a String value ,and throw out a Exception:
    java.lang.NullPointerException
    at java.lang.StringBuffer.append(StringBuffer.java:389)
    JNIEXPORT jint JNICALL Java_md_EMAP_thread_RubeMOTSSX_getMO
    (JNIEnv * env, jobject obj, jint connId, jobject mo){
         struct MO_msg MO;
         tssx_cmpp_api_debug_flag = 1;
         int result = CMPP_Get_MO((int)connId,&MO);
         if (result == 0){
              jclass cls = (*env)->GetObjectClass(env,mo);
              jfieldID msgId = (*env)->GetFieldID(env,cls,"msgId","J");
              jfieldID dest_Id = (*env)->GetFieldID(env,cls,"dest_Id","Ljava/lang/String;");
              jfieldID serviceId = (*env)->GetFieldID(env,cls,"serviceId","Ljava/lang/String;");          
              (*env)->SetLongField(env,mo,msgId,MO.msgID);               
              (*env)->SetCharField(env,mo,dest_Id,*destId);
              (*env)->SetCharField(env,mo,serviceId,MO.service_id);
         return result;
    Please help me!Thanks!

    bschauwe:Thank you for your help!
    Yes,just as you say,using NewString Or NewStringUTF can import a C char array into a Java String variable! But now I have another question,when i use these two functions ,i found that it cant deal with Chinese character!
    do you have such experiences to deal with another language charset?if you have ,can you tell me how to deal with it.

  • How to get shared photo streams in alphabetical order

    presentation is now in orde of sharing.

    Shared PhotoStreams are always in the order the photos are added and cannot be rearranged - they are streams.

  • In ios7, custom labels for phone contacts are all out of order. How can I get them back in alphabetical order?

    See above question.

    I had tried that several times with no luck.  Late last night I was finally able to get through  to the Verizon technical support who then called in Apple technical support.  It took 1 1/2 hours for them to figure it out and guide me through a fix.  So here's the deal .......... I use Yahoo mail and had left the "contacts" button in the on position.  Apparently Yahoo likes to go into your contacts and gather information and can leave it in shambles.  My advice is, go to settings, then mail, contacts, calendars.  Select any and all of your email accounts and go in and turn off their access to your information.  Leave it on for Icloud but none of the others.

  • Reading Each String From a text File

    Hello everyone...,
    I've a doubt in File...cos am not aware of File.....Could anyone
    plz tell me how do i read each String from a text file and store those Strings in each File...For example if a file contains "Java Tchnology forums, File handling in Java"...
    The output should be like this... Each file should contains each String....i.e..., Java-File1,Technology-File2...and so on....Plz anyone help me

    The Java� Tutorials > Essential Classes: Basic I/O

  • Reading a string.

    Hi experts.
    how can i read a string at a specified character.
    For ex: i have  astring like this.
    str = 'YUGFHKGHKHDKHHHGJK8HJBFXJKKFKJFJKFHJH'.
    so i have to read n.of charecters from starting of the string to charecter 8.
    Not with search option.
    Regards

    Hi,
    Thank you all.
    I know all these but in my program it is not workig..Don't know why...
    either split or search.Pls see the below sample code.
    DATA  : i_files like spflist occurs 0 with header line,
    DATA: w_files LIKE LINE OF  i_files.
    data: str1(200) type c,
          str2(200) type c.
    LOOP AT i_files INTO w_files.
        str = w_files-line.
        lin1 = STRLEN( str ).
        lin1 = lin1 - 1.(this is because there is one more '#' at the end of string)
        str = str+0(lin1).
        lin2 = STRLEN( str ).
        search str for '#'.
        split str at '#' into str1 atr2.    
        w_files-line = str.
        MODIFY i_files FROM w_files.
        CLEAR lin1.
      ENDLOOP.
    Suppose here str contains:
    str = '00000003379#212RegVNegNoticeHLA.aspx.xml'.
    So i am getting sy-subrc = 4 after search.
    and after split there are no values in str2..and str1 contains full string..
    Can any body tell me what may be the problem..?
    Regards

Maybe you are looking for

  • Clearing of Open items (per Vendor)

    Hi All, I would like to ask if there is a way to show multiple line items of a single vendor as multiple line items and not the sum of these line items during clearing in F-04. Right now, when clearing multiple line items of a single vendor, these li

  • How can I save my login for website ?

    My iPad no longer saves my login even when instructed to "remember me". It used to before the update last week. Is there a setting that is stopping Safari from doing this.

  • Problems with the NVS 5200m Discrete Graphics on T430s

    Hey all, I just received my T430s in the mail this last weekend, and I've been having some trouble with the Blue Screen of Death. It has happened twice so far, and both times the graphics card is unrecognized after the reboot. The first time it happe

  • Photo scroller question

    Hi - this ones quite comfusing for me as Im not the best at AS - there are three main problems i have with a horizontal photo scroller: 1. I need to load the photos into the swf externally but without specifically naming the photos to be loaded eg. i

  • BT Aqua phone

    Hi - my BT Aqua handset has suddenly gone wrong - instead of the usual display there is only strange symbols and numbers.  There is a dialling tone and you are able to ring out.  I have tried new batteries but has no effect.  Does anyone have any ide