Arrays and sorting

How would you sort an int array w/out using the sort algorithum given w/ java. Please also show all the steps...i have been trying to figure this one out for about 3 days now...help

Start by showing us the code to your homework assignment that you've completed so far. We can help you debug specific issues. When you post your code, please used the special tokens found at http://forum.java.sun.com/faq.jsp#format to format your code.

Similar Messages

  • Copy array and sort the numbers in the new array

    Hi!
    I have an array containing some digits where some of the digits are zeros. I want to copy the digits to another array but the zeros (well, I actually want to copy the zeros as well but I want to have them in the end of the new array).
    I suppose I need an if-statement that checks if the old array contains any zeros and in that if-statement copy the content to the new array and put the zeros in the end.
    This is my code so far and I don�t know how to go on from here:
    int[] new_array = new int[array.length];
              for (int i = 0; i < array.length; i++)
                   if (array[i] > 0)
                        new_array[i] = array;
                        new_array = array;
                   System.out.print(new_array[i] + " ");

    Roxxor wrote:
    I think I know how to do it but only if I can catch the digits bigger than zero.
    My code below just checks if there are positive digits and if there are, the whole old array is copied to the new one.Yes. Don't do that, you can see it's wrong.
    So my problem is that I don�t know how to catch the digits bigger than zero and copy them. Is there any built in java keyword that catches signs, number etc?
    if (array>=0)
         new_array[i] = array[i];
         new_array = array;
    Yes, there is such a keyword. And you are already using it correctly in your code. You are already testing if the array entry is bigger than zero. Your only problem is, you don't know what to do when it is. But now you've been given two hints about what to do.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Date array and Sorting

    I have a date array that i created from a database.  I am trying to sort the dates into the correct order with the upcoming on top.... the best would be that after the date has passed it would go to the bottom of the list. Can anyone tell me if I am on the right path with what I have so far and give me any hints?  thanks (the second loop give me an error)
    <!--- Declare query array --->
    <cfset dateArray = arraynew(1)>
    <!--Poppulate Array row by row--->
    <cfloop query="CDE_Dates2">
              <cfset dateArray[currentRow][1] = event_date>
    </cfloop>
    <!--- Sort Array Dates --->
    <cfloop index="i" from="1" to="#arrayLen(dateArray)#">
              <cfset dateVar = DateFormat(dateArray[i],"YYYY/MM/DD")>
    </cfloop>

    I think I read that as you want dates sored in an order something like this:  future dates at the top, sorted in ascending order (most imminent first to farthest future last), then past dates at the bottom in ascending order (oldest first to most recent past last).
    The easiest way would be to either do this when you query the database (in your CDE_Dates2) or do a query-of-query on CDE_Dates2.  You can do it using a union and adding an extra column for sorting.  Here's some SQL pseudo-code:
    SELECT dateColumn, otherColumn, anotherColumn, 0 AS sortOverride
    FROM someTable
    WHERE dateColumn > <cfqueryparam value="#Now()#" cfsqltype="cf_sql_date">
    UNION
    SELECT dateColumn, otherColumn, anotherColumn, 1 AS sortOverride
    FROM someTable
    WHERE dateColumn <= <cfqueryparam value="#Now()#" cfsqltype="cf_sql_date">
    ORDER BY sortOverride, dateColumn
    This will force the future dates to the top and put past dates at the bottom.
    You could do the same thing in a QofQ.
    -Carl V.

  • Scan array and sort

    Hello,
    In the attached VI, I would like to extract the first 50 points, then next 50 and so on (from the attached file), and build up an array as shown in the image file. 
    Any help will be greatly appreciated.
    Thanks,
    hiNi.
    Solved!
    Go to Solution.
    Attachments:
    array_scan.vi ‏10 KB
    1600pts.txt ‏32 KB
    end array.png ‏41 KB

    I was hoping to solve this without a loop...
    Jim
    You're entirely bonkers. But I'll tell you a secret. All the best people are. ~ Alice

  • HashMaps and Sorting issue.

    Hey,
    I was wondering what the most effective method of doing the following was:
    I have some directories which are a collection of <id, reference to either a directory or a file> sets. The file objects contain a hashmap which has some information about the file. I want to sort the directory the file is in, by the values in the hashmap of the file.
    Originally I had the directory as a hashmap, with the id the key and the reference to the directory or file the value. The plan was to put the values.getHashMap.values() in an array, and sort it. However, I'm not quite sure this would work. I'm also no longer sure if a hashmap is the most effective way of doing this.
    Any ideas? Should I elaborate? Should I get rid of hashmap all together in this case?
    Thanks,
    -S

    First call the entrySet() method of the Map and you'll get a Set of EntrySet objects. The EntrySet object contains the key and the value, so it's those you want to sort. You can make a List or an array of those EntrySet objects quite easily, and then with a suitable Comparator you can sort that List or array in the right order.

  • Anyone know how to add a string to a 1d array with file info, then be able to read back, display string, and sort data array.

    I need to store a data array and include text that describes what the data is. (using for various configuration files.) Anyway, I would like to be able to save the string as part of the txt file, and somehow read it back, remove the (various length string), and display it in an indicator. All the while, not causing too much problem with the initial data array.
    Thanks in advance!!

    There are several ways to do what you require. A simple method would be to use an ASCII text file. When writing one of those, you just need to basically build a gaint string starting with the description text you want. We like to call that a header. Once you've got the header, make some sort of delimiter like a bunch of "-" or two sets of ( EOL = End of Line = CRLF = \r\n ). After your delimiter, concatenate your array in string form or flatten your array from its native form into a string and tack it on the file (append).
    See the (very quick) example attached.
    Dan Press
    www.primetest.com
    Attachments:
    fileheader.vi ‏41 KB

  • Array is sorted backwards, and contains unwanted fields?....

    Hi all
    I am creating an array from the flashVars passed from html.
    the string in the html flashVars params looks like this:
    var1=01.jpg|02.jpg|03.jpg&var2=01.jpg|02.jpg
    So basically each var is a list of images separated with the
    bar sign "|"
    I am succesfully retreiving the flashVars into an
    actionScript array, then I create a new array of
    the listed images, using the split function:
    for(var sVar in flashVars){
    var stringVal = flashVars[sVar];
    images = stringVal.split("|");
    Now, when I loop through the images array and output the
    result, I get these values, in this order:
    [type Function]
    03.jpg
    02.jpg
    01.jpg
    What is [type Function] and how did it get in my array?
    Then, why are the array values sorted in reverse order (last
    image is first, first image is last)?....
    I hope you can help.
    seb ( [email protected])
    http://webtrans1.com | high-end web
    design
    An Ingenious WebSite Builder:
    http://sitelander.com

    hi
    var sVar:String =
    "01.jpg|02.jpg|03.jpg&var2=01.jpg|02.jpg";
    var my_array:Array = sVar.split("|");
    for (var i:Number = 0; i<=3; i++) {
    trace(my_array
    i hope that it'll help you

  • Finding objects in arrays, adding to a temp array and replace old with temp

    hi, I am currently modifying a hand analyser for a poker game. imagine a hand of a set of cards that can be from 5 up to whatever the game instructs, the analyser then has to match the hand to the rankings of best hands. so it has to map the hand to these possible besthands..
    Royal Flush (A,K,Q,J,10 of same suit)
    Straight flush(a running rank of same suit)
    4 of a kind(er... 4 of the same rank)
    full house(3 of a kind and a pair)
    flush(all same suit)
    straight(a running rank, A,2,3,4,5...,K)
    2 pair(a pair and a pair)
    1 pair(a pair)
    and a high Card(the highest card in a hand)
    the hand is sorted in ranks and suits to check for straights and flushes, and i have used a for loop to find any pairs, trips and quads for a hand. the problem i am having is the checking of two pairs. here is the loop i am using
    Hand temp = new Hand();//creates a temporary hand to place the matching cards into. hand is an array of cards.
          for (int i = 1; i < cards.size() - 1; i++) {//cards is the hand passed to be checked for two pairs
            if (cards.getCard(i).getRank() == cards.getCard(i + 1).getRank()) {
             /*checks if the card in i is the same as the next card, if true,
                then adds it to the temp hand.*/
              temp.addCard(cards.getCard(i));
              /*once the cards are passed to the temp hand,
                 it is removed from the cards hand.*/
              cards.removeCard(i);     
              temp.addCard(cards.getCard(i));
              cards.removeCard(i);
              System.out.println(temp + "check twopair");
              /*just a check to see if they are passed and removed from those hands
                 -- these work the first time around*/
              System.out.println(cards + "check remaining best hand");
            else if (temp.size() == 4) {
                /*if the temp hand as 4 cards, it means there are 2 pairs found,
                   it adds the next card in the cards hand as the kicker. since cards
                   is ranked by value, it will choose the highest card*/
              temp.addCard(cards.getCard(i));
    //a check to see if the card has been added to the hand
              System.out.println("adds the kicker to the 2 pair");
            if (temp.size() == 5) {
    //once the best cards have been dealt into temp, it is passed back to the hand, cards.
              kicker = (Card)temp.getCard(4);
              cards = temp;
              return true;
           /*if the check finds that there is no 2 pairs in the hands, the cards are set
              back to the original cards, and sorted by rank and passes over to the
              next test, which should be the check one pair*/
          cards = new Hand(originalCards);
          sortbyRank();
          return false;the loop finds the first pair alright, but coming around the second time, it doesnt seem to pick up on the second pair.
    in an example, consider a 7 card hand being passed to this analyser..
    3d, 7h, Ac, 3h, 6h, 7s, Kd. this gets sorted into ranks and become Ac, Kd, 7s, 7h, 6h, 3d, 3h. the first check would be the royal flush - lets ignore the way it works, and it fails anyway because the hand doesnt hold a royal flush, similarly, all the other tests will fail, from straight flush, 4 of a kind, full house, flush, straight, 3 of a kind and then we get to 2 pairs. in the first instance the loop will check Ac == K, it fails, and checks if the temp hand has 4, it fails and goes to i =2. it will check K to 7, fail and go to i = 3, 7h matches 7s, so puts that to temp, temp now equal 2, but not 4, so loops. this is where i messes up. it doesnt pick up the two pairs of 3s. any suggestions?

    I've never played poker so I had to look carefully at your question. This resulted in the following table. This suggests to me that any attempt at simplification will not be easy so I think I would have an analyser object with nine methods returning a boolean as to whether each test had been met. This seems a cleaner approach although it may be less efficient than your own.
                                                  Same   Same   Rank
                                                  Suit   Rank   Seq
    Royal Flush (A,K,Q,J,10 of same suit)           Y             Y
    Straight flush(a running rank of same suit)     Y             Y
    4 of a kind(er... 4 of the same rank)                  Y
    full house(3 of a kind and a pair)             0.5    0.5
    flush(all same suit)                            Y
    straight(a running rank, A,2,3,4,5...,K)                      Y
    2 pair(a pair and a pair)                              Y
    1 pair(a pair)                                         Y
    and a high Card(the highest card in a hand)

  • Help needed for storing and sorting objects.

    Hello
    I have an assignment and it is to create a guessing game, here is the question,
    In this assignment you are to write a game where a user or the computer is to guess a random
    number between 1 and 1000. The program should for example read a guess from the keyboard, and
    print whether the guess was too high, too low or correct. When the user has guessed the correct
    number, the program is to print the number of guesses made.
    The project must contain a class called Game, which has only one public method. The method must
    be called start(), and, when run it starts the game. The game continues until the user chooses to
    quit, either at the end of a game by answering no to the question or by typing 'quit' instead of a
    guess. After each game has been played, the program is to ask the user for a name and insert this
    together with the number of guesses into a high score list. When a game is started the program
    should print the entire high score list, which must be sorted with the least number of guesses first
    and the most last. Note, the list must be kept as long as the game-object is alive!
    each score also
    consists of the game time. In case there are two high scores with the same number of guesses, the
    game time should decide which is better. The game time starts when the first guess is entered and
    stops when the correct guess has been made. There should also be input checks in the program so
    that it is impossible to input something wrong, i.e. it should be impossible to write an non-numeric
    value then we are guessing a number, the only allowed answers for a yes/no question is yes or no,
    every other input should yield an error message an the question should be printed again.
    I understand how to code most of it, except I am not sure how to store the playerName, playerScore, playerTime and then sort that accordingly.
    I came across hashmaps, but that wont work as the data values can be the same for score.
    Is it only one object of lets say a highScore class, and each time the game finishes, it enters the values into an arrayList, I still dont understand how I can sort the array all at once.
    Should it be sorted once for score, then another array created and sorted again, I dont get it I am confused.
    Please help clarify this.

    Implode wrote:
    We had the arrayList/collections lecture today.
    I asked the teacher about sorting objects and he started explaining hashmaps and then he mentioned another thing which we will only be learning next term, I'm sure we must only use what we have learned.
    How exactly can this be done. I have asked a few questions in the post already.
    ThanksWell, there was probably a gap in the communication. Hash maps (or hash tables, etc.) are instance of Map. Those are used to locate a value by its unique key. Generally, to speed up access, you implement a hashing function (this will be explained hopefully in class). Think of name-value pairs that are stored where the name is unique.
    Contrast this with items that are sorted. Any List can be sorted because its elements are ordered. An ArrayList is ordered, generally, by the order you inserted the elements. However, any List can be given its own ordering via Comparable or Comparator. You can't do this with an ordinary Map. The purpose of a Map is speedy access to the name-value pairs, not sorting. The List likewise has different purposes, advantages, disadvantages, etc. List can be sorted.
    A Map is generally similar to a Set. A Set is a vanilla collection that guarnatees uniqueness of each element (note, not name-value pairs, but simple elements). There is one concrete class of Map that can be sorted, TreeMap, but I doubt your professor was referring to that. The values or the keys can be returned from the Map and sorted separately, but again, I doubt he was referring to that.
    Take a look at the Collections tutorial here on this site or Google one. It is fairly straightforward. Just keep in mind that things (generally) break down into Set, Map and List. There are combinations of these and different flavors (e.g., Queue, LinkedHashMap, etc.) But if you can learn how those three differ, you will go a long way towards understanding collections.
    (Oh, and be sure to study up on iterators.)
    - Saish

  • Java Binary Search and sorting in Java

    My program is suppose to search news articles and alphabetize all the words article individually of the text file. Right now the program alphabetizes all the words of the articles including the numbers. The text file will be located below the code. So basically i need to know how to alphabetize every articles words individually.
    //This program reads an input line from the reader put the worda into an array with a count and increases
    //the count each time a word is repeated. It then sorts the words alphabetically in the array and
    //then prints out the array. There are 4 different articles like this one in the text file
    <ID>58</ID>
    <BODY>Assets of money market mutual funds
    increased 720.4 mln dlrs in the week ended yesterday to 236.90
    billion dlrs, the Investment Company Institute said.
        Assets of 91 institutional funds rose 356 mln dlrs to 66.19
    billion dlrs, 198 general purpose funds rose 212.5 mln dlrs to
    62.94 billion dlrs and 92 broker-dealer funds rose 151.9 mln
    dlrs to 107.77 billion dlrs.
    </BODY>
    import java.util.StringTokenizer;
    import java.io.FileReader;
    import java.io.BufferedReader;
    import java.io.FileWriter;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.io.IOException;
    import java.io.FileNotFoundException;
    public class WordsFrequency
       public static void main(String[] args)
          // Initializations
          FileReader reader = null;
          FileWriter writer = null;
          // Open input and output files
          try
              reader = new FileReader("Reuters00.txt");
              writer = new FileWriter("WordsReport.txt");
          catch(FileNotFoundException e)
             System.err.println("Cannot find input file");
             System.exit(1);
          catch(IOException e)
           System.err.println("Cannot open input/output file");
           System.exit(2);
          // Set up to read a line and write a line
          BufferedReader in = new BufferedReader(reader);
          PrintWriter out = new PrintWriter(writer);
          out.println("Copied file is: Words followed by frequency");
          int count = 0;
           wordCount[] wordsArray = new wordCount[100000];
          boolean done = false;
          while(!done)
             String inputLine;
             try
                  inputLine= in.readLine();
             catch(IOException e)
                System.err.println("Problem reading input, program terminates. " );
                inputLine = null;
             if (inputLine == null)
               done = true;
         sortbyWords(wordsArray,count);
               for(int i = 0; i < count;i++)
                out.println(wordsArray.toString());
    else
                   StringTokenizer tokenizer = new StringTokenizer(inputLine);
              while(tokenizer.hasMoreTokens())
                   String token = tokenizer.nextToken();
                        int lengthofString = token.length();
                        char ch = token.charAt(lengthofString-1);
                        if(ch == '.' || ch == ',' || ch == '!' || ch == '?' || ch == ';')
                   token = token.substring(0,lengthofString-1);
    wordCount wordAndCount= new wordCount(token);
                        boolean skip = false;
                        for(int i = 0; i < count; i++)
                        if(token.equalsIgnoreCase(wordsArray[i].getWord()))
                             skip = true;
                             wordsArray[i].increaseFrequency();
                        if(skip == false)
                                  wordsArray[count] = wordAndCount;
                             count++;
    // Close files
    try
    in.close();
    catch(IOException e)
    System.err.println("Error closing file.");
    finally
    out.close();
         public static void sortbyWords(wordCount [] wArray, int size)
         wordCount temp;
         for (int j = 0; j < size-1; j++)
         for (int i = 0; i < size-1; i++)
         if (wArray[i].getWord().compareToIgnoreCase(wArray[i+1].getWord()) > 0)
              temp = wArray[i];
              wArray[i] = wArray[i + 1];
              wArray[i+1] = temp;
    Edited by: IronManNY on Sep 25, 2008 3:24 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    IronManNY wrote:
    My program is suppose to search news articles and alphabetize all the words article individually of the text file. Right now the program alphabetizes all the words of the articles including the numbers. The text file will be located below the code. So basically i need to know how to alphabetize every articles words individually.You want to strip out the numbers?

  • Help plz regarding array and DB

    hi ,
    i have a problem regarding sorting.
    I have 1 million records in my DB table.
    When i open my swing application i sort the records in table [ORDER BY col1,col3,col4] like that and want that order record ids .
    upto here no problem.i am getting the ids in array and in my swing application when i go next i get from arrray the next record.
    but the problem is since the volume of the table is large if any addition r deletion to the table is not reflecting in the sorted order array.
    i can simply again call the database and sort it an update the error.but it proved very insufficent way.
    so i am looking something to optmise the sorting.
    i got an idea like using view .but i am looking anybody knows any workaround alogrithm for this.
    sree

    Here is an example taken from the ResultSet API Doc's. Note the constant type of "TYPE_SCROLL_SENSITIVE" for the type of ResultSet. Is this what you are using? (I have not tried this, but it is the solution that is put forth in my books and documents.)
           Statement stmt = con.createStatement(
                                          ResultSet.TYPE_SCROLL_SENSITIVE,
                                          ResultSet.CONCUR_UPDATABLE);
           ResultSet rs = stmt.executeQuery("SELECT a, b FROM TABLE2");
           // rs will be scrollable, will not show changes made by others,
           // and will be updatable

  • K8N DIAMOND: New Raid array and old HD... I'm going crazy!!! Please

    Hi guys
    First, sorry for my poor english...
    My problem is:
    I bought two Raptor 36 Gb for my new raid array.
    I have my old HD Hitachi 250 Gb connected on sata 1.
    I connected my two raptor, on sata 3 and 4, I enabled all sata port and raid config for ports 3 and 4.
    I restart PC, typed F10 and set a stripe array with two raptor. All run ok...
    Restarted and boot with my copy of WinXP with SP2 and NF4 raid drivers.
    Installation found my array and my Hitachi;
    Hitachi with 4 partitions; C (os), D (driver), E (films), F (music)
    I create one partitions on my raid array, and it takes I: letter... So I formatted and start to copy os...
    Errors occurs when, restarting pc and resetting the boot to Hard disk (the order of booting is 1 - nvidia array, 2 - hitachi 250 gb), just before loading installation, It shows a black screen with an error: "there is an error in your hard disk bla bla bla.. try to control your connection or connect to windows help....bla bla..."
    The Raid array works properly, infact I try to disconnect my Hitachi from sata port 1 and all installation works (I'm writing from Win xp on the raid array).
    I tried to connect the hitachi on port 1 of silicon image controller.... same error..!!
    I'm desperate... I have all my life on my hitachi...
    I think that there's  a sort of conflict in drive letter assignement... I cant find a solution ..
    PLEASE HELP ME!!!

    Glad it worked, I had a feeling it would. 
    Quote
    One question for you.. on G: partition, there's a directory called "Windows", do you suggest me to format this partition??
    You can format it if you want to free up space, but unless you moved things around the My documents folder and everything in it is on that partition, along with anything you might of had on the old desktop during that Windows install.  You might have something you want there, I usually leave mine for a few month, and figure out if I have everything I need.
    Quote
    What I  have to do, if I need to reinstall WIn XP on first partition of raptor array??
    Things should be fine now as Windows marked the Hitachi drive as G. You should be able to reinstall without issue. But if you have a lot of sensitive info on the Hitachi, I would always disconnect the Hitachi if doing a fresh install.  Once windows is done installing, hook it back up.  But next time you shouldn't have to reconfigure NVRAID after disconnecting and reconnecting.
     

  • Add rows and sort JTable in the same program

    I would like to have a button to add rows to the JTable, but would also like to sort the data within the columns. This program can sort the data prior to clicking the 'add row' button. After I click the button, there is no new row, and I lose the ability to sort the column. Do you have any tips or advice as to what I can do to fix my program? Is it because I have to have the final code for SortFilterModel to work?
    Thanks
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class TableRowColumn extends JFrame
         private final static String LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
         JTable table;
         DefaultTableModel model;
         JPanel buttonPanel;
         JButton button;
         public TableRowColumn()
              Object[][] data = {
                        {"6", "K"},
                        {"5", "A"},
                        {"1", "Z"}
              String[] columnNames = {
                    "Number",
                    "Letter"
              model = new DefaultTableModel(data, columnNames);
                    //comment out this SortFilterModel line
                    final SortFilterModel sorter = new SortFilterModel(model);
                    //Change sorter to model
              table = new JTable(sorter);
              table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              //  Add table and a Button panel to the frame
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
              buttonPanel = new JPanel();
              getContentPane().add( buttonPanel, BorderLayout.SOUTH );
              button = new JButton( "Add Row" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        model.addRow( createRow() );
                        int row = table.getRowCount() - 1;
                        table.changeSelection(row, row, false, false);
                        table.requestFocusInWindow();
                 //Set up double click handler for column headers and sort
                 table.getTableHeader().addMouseListener(new MouseAdapter(){
                        public void mouseClicked(MouseEvent event)
                          //check for click
                          if (event.getClickCount() < 2) return;
                       //find column of click and
                       int tableColumn = table.columnAtPoint(event.getPoint());
                       //translate to table model index and sort
                       int modelColumn = table.convertColumnIndexToModel(tableColumn);
                       sorter.sort(modelColumn);
         private Object[] createRow()
              Object[] newRow = new Object[2];
              int row = table.getRowCount() + 1;
              newRow[0] = Integer.toString( row );
              newRow[1] = LETTERS.substring(row-1, row);
              return newRow;
         public static void main(String[] args)
              TableRowColumn frame = new TableRowColumn();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }

    I attempted to modify the code in the correct way, but I ran into a problem near the bottom with the model.addRow(rowData); line. It has an error saying it can't find the addRow method. If I take away the model part, it will compile, but it will cause an infinite loop when I push the 'Add Row' button within the program. I didn't expect that to work, and I think it isn't calling the right model.
    I am aware that my code organization and design skills are not very good. I am a fan of basic assembly and low-level hardware languages for the most part.
    Thanks for your advice so far, it has been helpful.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class TableRowColumn extends JFrame
         private final static String LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
         JTable table;
         public DefaultTableModel model;
         JPanel buttonPanel;
         JButton button;
         public TableRowColumn()
              Object[][] data = {
                        {"9", "C"},
                        {"5", "A"},
                        {"3", "B"}
              String[] columnNames = {
                    "Number",
                    "Letter"
              model = new DefaultTableModel(data, columnNames);
                    //comment out this SortFilterModel line
                    final SortFilterModel sorter = new SortFilterModel(model);
                    //Change sorter to model
              table = new JTable(sorter);
              table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              //  Add table and a Button panel to the frame
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
              buttonPanel = new JPanel();
              getContentPane().add( buttonPanel, BorderLayout.SOUTH );
              button = new JButton( "Add Row" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        sorter.addRow( createRow() );
                        int row = table.getRowCount() - 1;
                        table.changeSelection(row, row, false, false);
                        table.requestFocusInWindow();
                 //Set up double click handler for column headers and sort
                 table.getTableHeader().addMouseListener(new MouseAdapter(){
                        public void mouseClicked(MouseEvent event)
                          //check for click
                          if (event.getClickCount() < 2) return;
                       //find column of click and
                       int tableColumn = table.columnAtPoint(event.getPoint());
                       //translate to table model index and sort
                       int modelColumn = table.convertColumnIndexToModel(tableColumn);
                       sorter.sort(modelColumn);
         private Object[] createRow()
              Object[] newRow = new Object[2];
              int row = table.getRowCount() + 1;
              newRow[0] = Integer.toString( row );
              newRow[1] = LETTERS.substring(row-1, row);
              return newRow;
         public static void main(String[] args)
              TableRowColumn frame = new TableRowColumn();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    class SortFilterModel extends AbstractTableModel{
        public SortFilterModel(TableModel m){
            model = m;
            rows = new Row[model.getRowCount()];
            for (int i = 0; i < rows.length; i++) {
                rows[i] = new Row();
                rows.index = i;
    public void sort(int c){
    sortColumn = c;
    Arrays.sort(rows);
    fireTableDataChanged();
    public Object getValueAt(int r, int c) {
    return model.getValueAt(rows[r].index, c);
    public boolean isCellEditable(int r, int c){
    return model.isCellEditable(rows[r].index, c);
    public void setValueAt(Object aValue, int r, int c){
    model.setValueAt(aValue, rows[r].index, c);
    public int getRowCount() {
    return model.getRowCount();
    public int getColumnCount(){
    return model.getColumnCount();
    public String getColumnName(int c) {
    return model.getColumnName(c);
    public Class getColumnClass(int c){
    return model.getColumnClass(c);
    private class Row implements Comparable {
    public int index;
    public int compareTo(Object other) {
    Row otherRow = (Row)other;
    Object a = model.getValueAt(index, sortColumn);
    Object b = model.getValueAt(otherRow.index, sortColumn);
    if (a instanceof Comparable) {
    return ((Comparable)a).compareTo(b);
    else{
    return a.toString().compareTo(b.toString());
    public void addRow(Object[] rowData) {
    Row[] oldRows = new Row[rows.length];
    for (int i=0; i<rows.length; i++) {
    oldRows[i] = rows[i];
    rows = new Row[rows.length +1];
    for (int i=0; i < oldRows.length; i++) {
    rows[i] = oldRows[i];
    rows[oldRows.length] = new Row();
    rows[oldRows.length].index = oldRows.length;
    addRow (rowData);
    //model.addRow(rowData);
    fireTableDataChanged();
    private TableModel model;
    private int sortColumn;
    private Row[] rows;

  • Read and sort a semicolon seperated csv file

    Hi all,
    I need to sort the given csv file columnwise (alphabatically)... which means the corresponding row/rows also have to be sorted. need help.
    the csv file looks like:
    Wear;9;;;
    ;;;Image;1
    ;;;Area;2
    ;;;ner;3
    ;;;Content;1
    ;;;BContainer;1
    ;;;View;1
    VIEW;10;;;
    ;;;get;8
    ;;;ner;1
    ;;;View;1
    ACTIVE;21;;;
    ;;;Image;1
    ;;;get;7
    ;;;Area;4
    ;;;ner;1
    ;;;de.vw.mqbkombi.widgets.TransitionContainer;3
    ;;;Aget2;2
    ;;;ner2;1
    ;;;Sget;1
    ;;;iView;1
    The idea is to first sort Wear,VIEW, ACTIVE alphabatically (columnwise), making sure all the rows that they have are also moved.
    after that, alphabatically sort all the in-between rows.
    would appreciate the help from any expert on csv, excel table.

    doremifasollatido wrote:
    If you know that your columns never have embedded semicolons, you could call String.split to split each row at semicolons. Although you could leave the results in the arrays that String.split gives, you should probably create a Java class to represent each row. It will make your code easier to understand, and you could also more easily represent numeric values as numbers such as primitive int values (so that they sort correctly as numbers instead of as Strings). Then create a List of instances of that Java class, and sort the list using Collections.sort and a custom java.util.Comparator.Or indeed make it Comparable; but I'd agree this is definitely the way to go.
    Also, assuming that all your "secondary" rows, such as:
    ;;;Image;1
    ;;;Area;2
    refer to the preceding "primary" (Wear;9;;;), I'd suggest you fill in the unsupplied values for them. That will allow you to sort them all in one go. It might also be worth including a type in your "Row" class (maybe as an enum); alternatively you could have two different subclasses of a common Row class.
    Winston

  • Code for find the missing number in array without sorting/comparing in java

    Hi all,
    We have 1 to 100 number in an array, but one number is missing (from 1 to 100). we have to find it out without sorting or comparing of this missing number in array.
    please help me out to find the solution this query.
    regards & thanks
    Mohan Kumar
    Bangalore,
    India

    Maybe you could sum up the numbers you've got in your array and subtract the result from 5050 [the term [code](N*N+N)/2 where N is your upper bound (i.e. 100)]. You'll get the sum of all missing values (which in this case would be exactly the missing number). n.b. that you could genaeralize on that for arbitrary finite series.
    Kind Regards,

Maybe you are looking for