Help needed!2D array or ArrayList?

Hi,
I need help!
I have a dataset 'cellSig.txt' with data like '34.5,42,200,52,654,58,92.0,45.6,0.'
I need to write a program which would divide the dataset of 3000 seq (like above) into two datasets 'train' of size 2000 and 'test' of size 1000 selecting the seq randomly . The two datasets should not have duplicates and be similar to each other.
Using Arraylists I can randomly select the seqs and add them into a new file ..however how do I remove the selected seqs from the main file 'cellSig.txt' so that I can use the remaining 1000 seqs for the test file?
Any help would b greatly appreciated.
Regards
Nis

Crossposted:
http://forum.java.sun.com/thread.jspa?threadID=629166

Similar Messages

  • Newbie - help needed with array and dictionary objects

    Hi all
    Please see the code below. I've posted this code in another thread however the original issue was resolved and this is now a new issue I'm having although centered around the same code.
    The issue is that I'm populating an array with dictionary objects. each dictionary object has a key and it's value is another array of custom objects.
    I've found that the code runs without error and I end up with my array as I'm expecting however all of the dictionary objects are the same.
    I assume it's something to do with pointers and/or re-using the same objects but i'm new to obj-c and pointers so i am a bit lost.
    Any help again is very much appreciated.
    // Open the database connection and retrieve minimal information for all objects.
    - (void)initializeDatabase {
    NSMutableArray *authorArray = [[NSMutableArray alloc] init];
    self.authors = authorArray;
    [authorArray release];
    // The database is stored in the application bundle.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"books.sql"];
    // Open the database. The database was prepared outside the application.
    if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
    // Get the primary key for all books.
    const char *sql = "SELECT id, author FROM author";
    sqlite3_stmt *statement;
    // Preparing a statement compiles the SQL query into a byte-code program in the SQLite library.
    // The third parameter is either the length of the SQL string or -1 to read up to the first null terminator.
    if (sqlite3preparev2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
    // We "step" through the results - once for each row.
    // We start with Letter A...we're building an A - Z grouping
    NSString *letter = @"A";
    NSMutableArray *tempauthors = [[NSMutableArray alloc] init];
    while (sqlite3_step(statement) == SQLITE_ROW) {
    author *author = [[author alloc] init];
    author.primaryKey = sqlite3columnint(statement, 0);
    author.title = [NSString stringWithUTF8String:(char *)sqlite3columntext(statement, 0)];
    // FOLLOWING WAS LEFT OVER FROM ORIGINAL COMMENTS IN SQLBooks example....
    // We avoid the alloc-init-autorelease pattern here because we are in a tight loop and
    // autorelease is slightly more expensive than release. This design choice has nothing to do with
    // actual memory management - at the end of this block of code, all the book objects allocated
    // here will be in memory regardless of whether we use autorelease or release, because they are
    // retained by the books array.
    // if the author starts with the Letter we currently have, add it to the temp array
    if ([[author.title substringToIndex:1] compare:letter] == NSOrderedSame){
    [tempauthors addObject:author];
    } // if this is different letter, then we need to deal with that too...
    else {
    // create a dictionary to store the current tempauthors array in...
    NSDictionary *tempDictionary = [NSDictionary dictionaryWithObject:tempauthors forKey:@"authors"];
    // add the dictionary to our appDelegate-level array
    [authors addObject:tempDictionary];
    // now prepare for the next loop...
    // set the new letter...
    letter = [author.title substringToIndex:1];
    // remove all of the previous authors so we don't duplicate...
    [tempauthors removeAllObjects];
    // add the current author as this was the one that didn't match the Letter and so
    // never went into the previous array...
    [tempauthors addObject:author];
    // release ready for the next loop...
    [author release];
    // clear up the remaining authors that weren't picked up and saved in the "else" statement above...
    if (tempauthors.count > 0){
    NSDictionary *tempDictionary = [NSDictionary dictionaryWithObject:tempauthors forKey:@"authors"];
    [authors addObject:tempDictionary];
    else {
    printf("Failed preparing statement %s
    ", sqlite3_errmsg(database));
    // "Finalize" the statement - releases the resources associated with the statement.
    sqlite3_finalize(statement);
    } else {
    // Even though the open failed, call close to properly clean up resources.
    sqlite3_close(database);
    NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
    // Additional error handling, as appropriate...
    Message was edited by: dotnetter

    Ok, so I know what the issue is now...I just don't know enough to be able to resolve it!
    it's the tempAuthors objects.
    It's an NSMutableArray which is create on the line before the start of the WHILE loop.
    Having looked through the debugger, I can see that each dictionary object is created (with different codes which I assume are memory addresses) so all is well there. However, on each iteration of the loop in the middle there is an IF...ELSE... statement which in the ELSE section is clearing all objects from the tempAuthors array and beginning to repopulate it again.
    Looking at the containing dictionary objects in the debugger I can see that the tempAuthors object that each contains has the same code (again, I'm assuming this is a memory address) - so if I understand correctly, it's the same object...I assumed that when I created the dictionary using the dictionWithObject call that I would be passing in a copy of the object, but it's referencing back to the object which I then go on to change.
    Assuming the above is correct, I've tried several "stabs in the dark" at fixing it.
    I've tried relasing the tempAuthors object within the ELSE and initialising it again via an alloc...init - but this didn't work and again looking through the debugger it looks as though it was confused as to which object it was supposed to be using on the following iteration of the WHILE loop (it tried to access the released object).
    Having read a little more about memory management can someone tell me if I'm correct in saying that the above is because the tempAuthors object is declare outside the scope of the WHILE loop yet I then try to re-instantiate it within the loop (does that make sense???).
    Sorry for the long post...the more I can understand the process the less I can hopefully stop relying on others for help so much.
    I am continuing to read up on memory management etc but just not there yet.
    Regards
    Wayne

  • Help needed on accessing an arraylist

    Hello
    I have declared an arrayList globally as follows:
         ArrayList itemList = new ArrayList();I have then wrote a method to test if a user's session is new, if so set the arrayList into the session using setAttribute. The code then gets the attribute from the session and stores it in the variable listFromSession. This is also set into the session. The code is below:
    //ItemList itemList;
              if (ca.isNew()){
                   //itemList = new ArrayList();
              ca.setAttribute("itemlist", itemList);
              ArrayList listFromSession = (ArrayList)ca.getAttribute("itemList");
              listFromSession.add(c);
              ca.setAttribute("itemList", listFromSession);I have then tried to retrieve elements from the arrayList. Code is below, but im not sure if im trying to access the arrayList as you would a normal array:
    ArrayList listFromSession = (ArrayList)ca.getAttribute("itemList");
                        for (int i = 0; i < listFromSession.length; i++){
                             int amt = listFromSession.getprodQuant(i);
                             int id = listFromSession.getStockID(i);
                             String name = listFromSession.getprodName(i);
                             float price = listFromSession.getprodPrice(i);
                             float totalPrice = amt * price;
                             out.println("<TD>" + id + "</TD>");
                             out.println("<TD>" + name + "</TD>");
                             out.println("<TD>" + amt + "</TD>");
                             out.println("<TD>" + price + "</TD>");
                             out.println("<TD>" + totalprice + "</TD>");
                        }For example, i did originally have int amt = listFromSession(i).getprodQaunt; and so forth but that threw the same error: cannot find symbol getProdQuant even when I put code it in the example above.
    Basically the compiler cannot find the get methods nor the variable length(), ive tried size() but it dosn't like that either
    Can anyone help?
    Thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Can anyone understand as to why my arraylist cannot be accesssed or return the elements?
    Is it because the initialization is outside of the method that is accessing the list?
    package cart;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.Enumeration;
    import cart.CartItem;
    public class CartSession extends HttpServlet
         private HttpSession ca = null;
         private int numProducts = 0;
         ArrayList itemList = new ArrayList();
         ArrayList listFromSession = new ArrayList();
           public void doPost(HttpServletRequest request,
                                   HttpServletResponse response)
                throws ServletException, IOException
             response.setContentType("text/html");
              PrintWriter out = response.getWriter();
              int currentProduct = Integer.parseInt(request.getParameter("stock"));
              String currentName = request.getParameter("name");
              float currentPrice = Float.parseFloat(request.getParameter("price"));
              String am = request.getParameter("Amount");
              if (am == null) am = "1";
              int currentAmount = Integer.parseInt(am);
              cart.CartItem c = new cart.CartItem(currentProduct, currentName, currentPrice, currentAmount);
              ca = request.getSession();
              //ItemList itemList;
              if (ca.isNew()){
                   //itemList = new ArrayList();
              ca.setAttribute("itemlist", itemList);
              ArrayList listFromSession = (ArrayList)ca.getAttribute("itemList");
              listFromSession.add(c);
              ca.setAttribute("itemList", listFromSession);
              ca.setAttribute("currentProd", c);
              sendPage(response);
         private void sendPage(HttpServletResponse reply) throws IOException
                        reply.setContentType("text/HTML");
                        PrintWriter out = reply.getWriter();
                        out.println("<HTML>");
                        out.println("<HEAD>");
                        out.println("<TITLE></TITLE>");
                        out.println("<HEAD>");
                        out.println("<BODY><H1>Your Shopping Cart</H1>");
                        out.println("<CENTER>");
                        out.println("<BR><BR><BR>");
                        //cart.removeAttribute("currentProd");
                             out.println("<TABLE BGCOLOR=Aqua BORDER=2>");
                             out.println("<TR>");
                             out.println("<TH>Stock ID</TH>");
                             out.println("<TH>Product</TH>");
                             out.println("<TH>Quantity</TH>");
                             out.println("<TH>Unit price</TH>");
                             out.println("<TH>Total price</TH>");
                             out.println("</TR>");
                        ArrayList listFromSession = (ArrayList)ca.getAttribute("itemList");
                        for (int i = 0; i < listFromSession.length; i++){
                             int amt = listFromSession.getprodQuant(i);
                             int id = listFromSession.getStockID(i);
                             String name = listFromSession.getprodName(i);
                             float price = listFromSession.getprodPrice(i);
                             float totalPrice = amt * price;
                             out.println("<TD>" + id + "</TD>");
                             out.println("<TD>" + name + "</TD>");
                             out.println("<TD>" + amt + "</TD>");
                             out.println("<TD>" + price + "</TD>");
                             out.println("<TD>" + totalprice + "</TD>");
                             //See if user wants more items
                             out.println("<FORM METHOD=POST ACTION='paymentform.html'>");
                             out.println("Would you like to<BR>");
                             out.println("<INPUT TYPE=SUBMIT VALUE=\" Add more items \">");
                             out.println("<FORM METHOD=POST ACTION='paymentform.html' \">");
                             out.println("<INPUT TYPE=SUBMIT VALUE=\" Check Out \">");
                        out.println("</TABLE>");
                        out.println("</FORM>");
                        out.println("</CENTER>");
                        out.println("</BODY>");
                        out.println("</HTML>");
                        out.flush();
    {code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Help needed on array problem

    Hi All
    I am trying to write a code using arrays, but I am stuck!
    I put the code below so that you can compile and see it.
    What I am trying to do is, I have customers with account numbers and balance, I get these values from console, put them in an array and at the end show them what they entered in a pop-up window. that's very very simple.
    Although I have a counter in while loop and increment it each cycle, I can not put the values to the array. When the next input comes, the former is overwritten.
    I am not very used to java. I've always used c++ till now, but for this thing, I have to write it in java. I could not find a way.
    any suggestion highly appreciated.
    thank you
    import java.util.Scanner;
    import javax.swing.JOptionPane;
    public class Customer
         private static double account_number;     
         private static double balance;
         public static void main (String args[])
              Customer[] customers = new Customer[2];
              int counter = 0;
              while(counter < 2){
              Scanner input = new Scanner(System.in);
              System.out.println("What is your account number?");
                   customers[counter].account_number = input.nextDouble();
              System.out.println("What is your balance?");
                   customers[counter].balance = input.nextDouble();
              counter ++;
              for(counter=0;counter<2;counter++){
              System.out.println("Account number" + customers[0].account_number);
    }

    Although I have a counter in while loop and increment
    it each cycle, I can not put the values to the
    array. When the next input comes, the former is
    overwritten.
    I am not very used to java. I've always used c++ till
    now, but for this thing, I have to write it in java.
    I could not find a way.
    public class Customer
         private static double account_number;     
         private static double balance;
         public static void main (String args[])
              Customer[] customers = new Customer[2];
              int counter = 0;
              while(counter < 2){
              Scanner input = new Scanner(System.in);
    System.out.println("What is your account number?");
    customers[counter].account_number = input.nextDouble();[snipped the rest ]
    The account_number and balance members are static members,
    i.e. they belong to the class itself and all the Customer objects share
    those members. Remove the static part and you're almost in
    business.
    There's more though: in C++ when you declare an array of two Customers,
    enough room is allocated for two Customer objects and the default
    constructor is called for both objects.
    Not so in Java: defining an array like you did above (and there is no
    other way to do that) just defines an array containing two references
    (read: pointers) to a Customer object. The references are null though;
    you still have to instantiate those two customer objects like this:
    for (int i= 0; i < customers.length; i++)
       customers= new Customer();
    The only reason you didn't get a NullPointerException is because those
    two member variables were declared to be static (which is wrong).
    Static member variables can be accessed without an actual object
    in scope, i.e. ((Customer)null).account_number would have worked.
    But again: you don't want these things to be static.
    kind regards,
    Jos

  • Need help with an array

    I'm working on creating an array that is basically a deck of cards, this is the problem.
    I'm getting this error:
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
      void main()
        final int ARRAY_SIZE = 52;
        String[] deck = new String[ARRAY_SIZE];
        String[] cardValue = new String[]{"A","2","3","4","5","6","7","8","9","T","J","Q","K"};
        String[] cardSuit = new String[]{"C","H","D","S"};
        for (int count = 0; count < ARRAY_SIZE; count++)
          deck[count]= cardValue[count] + cardSuit[count];
        }I Know that this is because cardSuit is reaching the end of the array, but how do I keep this from happening and make it start from the beginning until i reach the end of the cardValue array?

    By the way thanks for the help guys, I'm in a pinch for this assignment and I appreciate all of the help.
      void main()
        final int ARRAY_SIZE = 52;
        String[] deck = new String[ARRAY_SIZE];
        String[] cardValue = new String[]{"A","2","3","4","5","6","7","8","9","T","J","Q","K"};
        String[] cardSuit = new String[]{"C","H","D","S"};
        for (int count = 0; count < ARRAY_SIZE; count++)
          deck[count]= cardValue[count % 13] + cardSuit[count % 4];
          showCards(deck);
      void showCards(String [] list)
        String cards = ("card");
        for (int count = 0; count < list.length; count++)
          print (cards);
      This is what I'm talking about. I need to be able to call the showCards method and have it display whatever cards are currently in the players hand regardless of how many cards there are. I believe that I'm right when I used the void declaration because I don't want it the method to return anything to itself.
    Right now with the code as is, i get "card" typed out 52 times.
    First how do I go about having it print out the complete deck and the order that they are in?
    Is there a way to create the deck in pre-sorted like I have below?
    This was the assignment:
    Write a ConsoleProgram to create a deck of playing cards, shuffle them, and deal out 5 cards to the player. To do this:
    � You will need an array of 52 cards. In the basic version of this program, each card is a string in the form �XY�, where X is the rank (A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K, A) and Y is a letter designating the suite (C, H, D, S).
    � You will need to shuffle the cards by swapping the positions of two randomly selected cards in the array. For this, you should write and use three methods:
    o randRange � a method which takes 2 parameters: a minimum integer and a maximum integer. It creates a random integer in this range and returns it.
    o swap � a method which takes 3 parameters: an array of cards and two subscripts. It swaps the array elements with the given subscripts and returns nothing in its name.
    o shuffle � a method which takes 2 parameters: an array of cards and a number of times to swap cards. It shuffles by swapping two randomly selected cards the desired number of times (a possibly different pair each time). It returns nothing in its name (so it is a void method).
    � You will need an array of 5 cards for the player�s hand. After shuffling the deck, you will fill this array with the first 5 cards from the deck.
    � Display the unshuffled deck, then the shuffled deck, and finally the player�s hand. Indicate which is which in the output. For example, the output of one program run might look like this: Unshuffled: 2C, 3C, 4C, 5C, 6C, 7C, 8C, 9C, TC, JC, QC, KC, AC, 2D, 3D, 4D, 5D, 6D, 7D, 8D, 9D, TD, JD, QD, KD, AD, 2H, 3H, 4H, 5H, 6H, 7H, 8H, 9H, TH, JH, QH, KH, AH, 2S, 3S, 4S, 5S, 6S, 7S, 8S, 9S, TS, JS, QS, KS, AS Shuffled: 2C, QC, 3S, 9C, 9S, 6C, 6H, 3C, QH, 2H, 8C, 9H, AH, 4S, AS, TH, 6D, 3D, 2S, 8S, 5C, TC, 4C, 4D, 7C, AD, 9D, JD, 4H, 5S, KH, 7H, JS, 8D, TD, KC, 3H, 2D, KD, AC, KS, JC, 5H, JH, 8H, 5D, 7S, TS, QD, 7D, 6S, QS Your Hand: 2C, QC, 3S, 9C, 9S

  • Multi-part form problem (array & session help needed)

    I have a multi-part form that consists of 3 pages(forms) which each save data to the session. When the final form is complete, I insert the session variables to the DB via a FINISH button.
    I now want to take another step. Page 2 of this multi-part form allows users to add "items". Presently, they can add only 1 item, and move the page 3 by hitting a next button. I would like to add a "Add another item" button that goes to the page 2 form again, allowing more items to be entered. I believe I need an array/table to do this, but don't know how I might do this in the session.
    Is it possible to create an array in the session? If so, how? If not, how might I approach this?
    I am trying to avoid inserting to the database (a remote db) until after a "preview" page following the form.
    Any ideas? Thx in advance.

    Hi,
    This forum thread may help you:
    http://swforum.sun.com/jive/thread.jspa?forumID=123&threadID=50623
    Thanks,
    Creator Team.

  • Re: Beginner needs help using a array of class objects, and quick

    Dear Cynthiaw,
    I just read your Beginner needs help using a array of class objects, and quick of Dec 7, 2006 9:25 PM . I really like your nice example.
    I also want to put a question on the forum and display the source code of my classe in a pretty way as you did : with colors, indentation, ... But how ? In html, I assume. How did you generate the html code of your three classes ? By help of your IDE ? NetBeans ? References ?
    I already posted my question with six source code classes ... in text mode --> Awful : See "Polymorphism did you say ?"
    Is there a way to discard and replace a post (with html source code) in the Sun forum ?
    Thanks for your help.
    Chavada

    chavada wrote:
    Dear Cynthiaw,
    I just read your Beginner needs help using a array of class objects, and quick of Dec 7, 2006 9:25 PM . I really like your nice example.You think she's still around almost a year later?
    I also want to put a question on the forum and display the source code of my classe in a pretty way as you did : with colors, indentation, ... But how ?Just use [code] and [/code] around it, or use the CODE button
    [code]
    public class Foo() {
      * This is the bar method
      public void bar() {
        // do stuff
    }[/code]

  • Hello guys need help with reverse array

    Need help reversing an array, i think my code is correct but it still does not work, so im thinking it might be something else i do not see.
    so far the input for the array is
    6, 25 , 10 , 5
    and output is still the same
    6 , 25 , 10 , 5
    not sure what is going on.
    public class Purse
        // max possible # of coins in a purse
        private static final int MAX = 10;
        private int contents[];
        private int count;      // count # of coins stored in contents[]
         * Constructor for objects of class Purse
        public Purse()
           contents = new int[MAX];
           count = 0;
         * Adds a coin to the end of a purse
         * @param  coinType     type of coin to add
        public void addCoin(int coinType)
            contents[count] = coinType;
            count = count + 1;
         * Generates a String that holds the contents of a purse
         * @return     the contents of the purse, nicely formatted
        public String toString()
            if (count == 0)
                return "()";
            StringBuffer s = new StringBuffer("(");
            int i = 0;
            for (i = 0; i < count - 1; ++i)
                s.append(contents[i] + ", "); // values neatly separated by commas
            s.append(contents[i] + ")");
            return s.toString();
         * Calculates the value of a purse
         * @return     value of the purse in cents
        public int value()
            int sum = 0; // starts sum at zero
            for( int e : contents) // sets all to e
                sum = sum + e; //finds sum of array
            return sum; //retur
         * Reverses the order of coins in a purse and returns it
        public void reverse()
           int countA = 0;
           int x = 0;
           int y = countA - 1;                                          // 5 - 1 = 4
           for (int i = contents.length - 1; i >=0 ; i--)                        // 4, 3 , 2, 1, 0
                countA++;                                             // count = 5
            while ( x < y)
                int temp = contents[x];
                contents[x] = contents [y];
                contents [y] = temp;
                y = y- 1;                                         // 4 , 3 , 2, 1 , 0
                x = x + 1 ;                                             // 0 , 1,  2  , 3 , 4
    }

    ok so i went ahead and followed what you said
    public void reverse()
          int a = 0;
          int b = contents.length - 1;
          while (b > a)
              int temp = contents[a];
              contents[a] = contents;
    contents [b] = temp;
    a++;
    b--;
    }and its outputting { 0, 0, 0, 0}
    im thinking this is because the main array is has 10 elements with only 4 in use so this is a partial array.
    Example
    the array is { 6, 25, 10, 5, 0, 0, 0, 0, 0, 0,}
    after the swap
    {0, 0 , 0 , 0, 0 , 0 , 5 , 10 , 25, 6}
    i need it to be just
    { 5, 10, 25, 6}
    so it is swapping the begining and end but only with zeroes the thing is i need to reverse the array without the zeroes                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Need help with an array function

    I'm using the array index function and i would like to be able to control what elements go out on it.  For example, if i wanted only the first element to go out, i don't want the second element to send out zero.  Is there any way i can control what elements leave the array index function.  I also don't understand what the index inputs do on that function either.  If anyone has any advice on the application or can modify it in any way, please help.
    Attachments:
    Array and for loop.vi ‏1190 KB

    The index inputs determine what elements are retrieved. For example of you would wire a 10 and a 20 to your two index inputs, you would bet element #10 and element #20 of your array. You can resize it to get any desired number of elements.
    If you don't wire the index inputs, you'll get the first two elements.
    If you only wire the top index input (e.g a 10), you'll get element #10 and #11.
    LabVIEW Champion . Do more with less code and in less time .

  • Help needed about regex usage.

    hi all,
    i am kind of new to java.util.regex, and i can't solve this problem:
    i have a big string, that actually represents the text code of a method. in this method, i have an object, called, let's say "visitor" and i call several non static methods of it. i need to search this string and put into an ArrayList<String> all the occurrences of visitor, the method called, and its parameters.
    if i wasn't very clear, here is an example:
    the input string: "public void test_add()
              TemplateTestMethodVisitor visitor = new TemplateTestMethodVisitor(XMLArrayListTest.class);
              XMLArrayListComparer comparer = new XMLArrayListComparer();
              while(visitor.moveNext())
                   fillArrayList(visitor);
                   Exception exception = null;
                   try
                        _testedArray.add(visitor.getParameterAsInt("position"), ValueFactory.getMemberValue(visitor,
                                  visitor.getParameterAsString("type"), "ElementValue"));
                   catch(Exception e)
                        exception = e;
                   ExceptionValidator.validateException(visitor, exception);
                   if(exception != null)
                        continue;
                   VisitorAssert.assertEquals(visitor, "The content of the array list is not as expected.",
                             visitor.getResultAsCollectionData("List"), _testedArray, comparer);
    and i need to obtain an ArrayList<String> with {"visitor.moveNext()", "visitor.getParameterAsInt("position")" , "visitor.getParameterAsString("type")", "visitor.getResultAsCollectionData("List")"}. and it would be very helpful for me to do this using regex, but i can't think of a right pattern...
    thank you all.

    import java.io.*;
    import java.util.regex.*;
    public class TestRegexp {
      public static void main(String[] argv) {
        Pattern p = Pattern.compile("visitor\\..*?\\(.*?\\)");
        try {
          BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
          String line;
          while((line = in.readLine()) != null) {
            Matcher m = p.matcher(line);
            while(m.find()) {
              System.out.println(m.group());
        } catch(IOException e) {
          e.printStackTrace();
    }

  • Help needed in constructing a tree

    Help needed in constructing a tree. I was wondering if some one can suggest me how to add messages in the second column for both the parent node and child elements.
    I was able to create a tree succefully, but want to add some description in the second column for the first column elements, for both parent and child elements.
    Please suggest me how to add the arrays to second column for parent and child nodes.
    Solved!
    Go to Solution.
    Attachments:
    Tree_fix.vi ‏15 KB

    The Child Text parameter is the one you are searching for. It accepts a 1D string array for the following columns.
    hope this helps,
    Norbert
    CEO: What exactly is stopping us from doing this?
    Expert: Geometry
    Marketing Manager: Just ignore it.

  • I need an Array in my JAVA CODE

    I need an array in my java code for my last class in my Java 1 course
    my code does compile in dos using javac,....and it does work
    It is a mortgage calculator for 3 loans of 3 different years loaned,.... and each have a different interest rate.
    I need to have my code in an ARRAY for my last week .
    any help would be appreciated
    here is my code :
    import java.text.*;           //20 May 2008, Revision ...many
    import java.io.IOException;
    class memortgage     //program class name
      public static void main(String[] args) throws IOException
        double amount,moPay,totalInt,principal = 200000; //monthly payment, total interest and principal
        double rate [ ] = {.0535, .055, .0575};          //the three interest rates
        int [ ] term = {7,15,30};                        //7, 15 and 30 year term loans
        int time,ratePlace = 0,i,pmt=1,firstIterate = 0,secondIterate = 0,totalMo=0;
        char answer,test;
        boolean validChoice;
        System.in.skip(System.in.available());           //clear the stream for the next entered character
        do
          validChoice = true;
          System.out.println("What Choice would you Like\n");
          System.out.println("1-Interest rate of 5.35% for 7 years?");       //just as it reads for each to select from
          System.out.println("2-Interest rate of 5.55% for 15 years?");
          System.out.println("3-Interest rate of 5.75% for 30 years?");
          System.out.println("4-Quit");
          answer = (char)System.in.read();
          if (answer == '1')  //7 yr loan at 5.35%
            ratePlace = 0;
            firstIterate = 4;
            secondIterate = 21;
            totalMo= 84;
          else if (answer == '2') //15 yr loan at 5.55%
            ratePlace = 1;
            firstIterate = 9;      //it helps If I have the correct numbers to calcualte as in 9*20 to equal 180...that why I was off -24333.76
            secondIterate = 20;    //now it is only of -0.40 cents....DAMN ME
            totalMo = 180;
          else if (answer == '3') //30 yr loan at 5.75%
            ratePlace = 2;
            firstIterate = 15;
            secondIterate = 24;
            totalMo = 360;
          else if (answer == '4') //exit or quit
            System.exit(0);
          else
            System.in.skip(System.in.available());               //validates choice
            System.out.println("Invalid choice, try again.\n\n");
            validChoice = false;
        }while(!validChoice);  //when a valid choice is found calculate the following, ! means not, similar to if(x != 4)
        for(int x = 0; x < 25; x++)System.out.println();
        amount = (principal + (principal * rate[ratePlace] * term[ratePlace] ));
        moPay = (amount / totalMo);
        totalInt = (principal * rate[ratePlace] * term[ratePlace]);
        DecimalFormat df = new DecimalFormat("0.00");
        System.out.println("The Interest on $" + (df.format(principal) + " at " + rate[ratePlace]*100 +
        "% for a term of "+term[ratePlace]+" years is \n" +"$"+ (df.format(totalInt) +" Dollars\n")));
        System.out.println("\nThe total amount of loan plus interest is $"+(df.format(amount)+" Dollars.\n"));
        System.out.println("\nThe Payments spread over "+term[ratePlace]* 12+" months would be $"+
        (df.format (moPay) + " Dollars a month\n\n"));
        System.in.skip(System.in.available());
        System.out.println("\nWould you like to see a planned payment schedule? y for Yes, or x to Exit");
        answer = (char)System.in.read();
        if (answer == 'y')
          System.out.println((term[ratePlace]*12) + " monthly payments:");
          String monthlyPayment = df.format(moPay);
          for (int a = 1; a <= firstIterate; a++)
            System.out.println(" Payment Schedule \n\n ");
            System.out.println("Month Payment Balance\n");
            for (int b = 1; b <= secondIterate; b++)
              amount -= Double.parseDouble(monthlyPayment);
              System.out.println(""+ pmt++ +"\t"+ monthlyPayment + "\t"+df.format(amount));
            System.in.skip(System.in.available());
            System.out.println(("This Page Is Complete Press [ENTER] to Continue"));
            System.in.read();
    }

    here is what was commented from my instructor for my week 4...is what you sen in the code....but I fixed loan 2 tonight
    "Week 4 Great work, the numbers were a little off on the 1st and 2nd loans. Next time
    try putting the values you displayed in an array. "
    import java.text.*;           //20 May 2008, Revision ...many
    import java.io.IOException;
    class memortgage     //program class name
      public static void main(String[] args) throws IOException
        double amount,moPay,totalInt,principal = 200000; //monthly payment, total interest and principal
        double rate [ ] = {.0535, .055, .0575};          //the three interest rates
        int [ ] term = {7,15,30};                        //7, 15 and 30 year term loans
        int time,ratePlace = 0,i,pmt=1,firstIterate = 0,secondIterate = 0,totalMo=0;
        char answer,test;
        boolean validChoice;
        System.in.skip(System.in.available());           //clear the stream for the next entered character
        do
          validChoice = true;
          System.out.println("What Choice would you Like\n");
          System.out.println("1-Interest rate of 5.35% for 7 years?");       //just as it reads for each to select from
          System.out.println("2-Interest rate of 5.55% for 15 years?");
          System.out.println("3-Interest rate of 5.75% for 30 years?");
          System.out.println("4-Quit");
          answer = (char)System.in.read();
          if (answer == '1')  //7 yr loan at 5.35%
            ratePlace = 0;
            firstIterate = 4;
            secondIterate = 21;
            totalMo= 84;
          else if (answer == '2') //15 yr loan at 5.55%
            ratePlace = 1;
            firstIterate = 9;      //it helps If I have the correct numbers to calcualte as in 9*20 to equal 180...that why I was off -24333.76
            secondIterate = 20;    //now it is only of -0.40 cents....DAMN ME
            totalMo = 180;
          else if (answer == '3') //30 yr loan at 5.75%
            ratePlace = 2;
            firstIterate = 15;
            secondIterate = 24;
            totalMo = 360;
          else if (answer == '4') //exit or quit
            System.exit(0);
          else
            System.in.skip(System.in.available());               //validates choice
            System.out.println("Invalid choice, try again.\n\n");
            validChoice = false;
        }while(!validChoice);  //when a valid choice is found calculate the following, ! means not, similar to if(x != 4)
        for(int x = 0; x < 25; x++)System.out.println();
        amount = (principal + (principal * rate[ratePlace] * term[ratePlace] ));
        moPay = (amount / totalMo);
        totalInt = (principal * rate[ratePlace] * term[ratePlace]);
        DecimalFormat df = new DecimalFormat("0.00");
        System.out.println("The Interest on $" + (df.format(principal) + " at " + rate[ratePlace]*100 +
        "% for a term of "+term[ratePlace]+" years is \n" +"$"+ (df.format(totalInt) +" Dollars\n")));
        System.out.println("\nThe total amount of loan plus interest is $"+(df.format(amount)+" Dollars.\n"));
        System.out.println("\nThe Payments spread over "+term[ratePlace]* 12+" months would be $"+
        (df.format (moPay) + " Dollars a month\n\n"));
        System.in.skip(System.in.available());
        System.out.println("\nWould you like to see a planned payment schedule? y for Yes, or x to Exit");
        answer = (char)System.in.read();
        if (answer == 'y')
          System.out.println((term[ratePlace]*12) + " monthly payments:");
          String monthlyPayment = df.format(moPay);
          for (int a = 1; a <= firstIterate; a++)
            System.out.println(" Payment Schedule \n\n ");
            System.out.println("Month Payment Balance\n");
            for (int b = 1; b <= secondIterate; b++)
              amount -= Double.parseDouble(monthlyPayment);
              System.out.println(""+ pmt++ +"\t"+ monthlyPayment + "\t"+df.format(amount));
            System.in.skip(System.in.available());
            System.out.println(("This Page Is Complete Press [ENTER] to Continue"));
            System.in.read();
    }

  • Help with method/array lab

    I need some help creating an array of students in my lab, using a method. I'm fairly confused on how to do this. This is a sample of my code, i've deleted a lot of the stuff further down thats not needed atm.
    Anyhow, I understand how arrays work and whatnot, but have no clue as to how to create the array in the method. Any help please! (The last few lines of posted code is where the array should go)
    import java.util.Scanner;
    import java.io.*;
    public class Lab6
        public static void main(String[] args)
            // Fill in the body according to the following comments
             Scanner keyboard = new Scanner(System.in);
             // Input file name
         String fileName = getFileName(keyboard);
             // Input number of students
         int numberOfStudents = FileIOHelper.getNumberOfStudents(fileName);
             // Input all student records and create Student array and
         Student [] studentAry = new Student [numberOfStudents];
             // integer array for total scores
        // Given a Scanner in, this method prompts the user to enter
        // a file name, inputs it, and returns it.
        private static String getFileName(Scanner keyboard)
             String fileName;
         System.out.print("Enter input file name: ");
        fileName = keyboard.nextLine();
        return fileName;
        // Given the number of students records n to input, this
        // method creates an array of Student of the appropriate size,
        // reads n student records using the FileIOHelper, and stores
        // them in the array, and finally returns the Student array.
        private static Student[] getStudents(int n)
            // Fill in the body
        }

    Oh btw, this is sample code givin to me by my professor that may help?
            // Copy a student from the file to the array
              Student aStudent = FileIOHelper.getNextStudent();
              studentAry[0] = aStudent;
              // Copy another student to the array
              aStudent = FileIOHelper.getNextStudent();
              studentAry[1] = aStudent;
              // Get student information from the array
              String name = studentAry[1].getName();
              int s1 = studentAry[1].getScore(1);
              int s2 = studentAry[1].getScore(2);
              int s3 = studentAry[1].getScore(3);

  • Help creating a array

    Hi i've got a simple guessing game. Which the user has to guess the right number. A hint will be displayed if the users guess is cold, warm or hot. Each game has 8 rounds in which they have to guess 8 numbers, but each number they have 3 attempts to guess if they guess correct it will say you won and add one to games won and if they lose on there 3rd attempt it will show a message saying sorry and show the number. At the end of the 8 rounds it will give them a result depending on how many games were won.
    I have managed to do all this so far, but the problem that i have is i need to make this game so it can be played by multiplayers. A message will ask how many players, max 6. The computer has to have one random number for each round. Each player plays 8 rounds, taking turns in guessing the number. Once 8 rounds are up the program should print a message saying which player won most games.
    I'm not really sure how to go about doing this? I'm guessing i need an array to store each players wins and then an if statement or switch statement saying if player 1 > player 2 and for all of them then player one wins? But even this the array still confuses me not really sure how to go about it?
    Any help is much appreciated, heres my code so far.
    package assessment;
    import javax.swing.JOptionPane;
    public class guessingGame{
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              final String win = "You won";
              final String lose = "Try again";
                        final int MAX_GUESS = 3;
              final int RANGE = 10;
              int ROUNDS = 8;
              int players = 0;
              int computersNumber = 0;
              int usersGuess = 0;
              int winCount = 0;
              int i, j = 0;
              String userInput;
              String output;
              String playersString;
                        int [] myArray = new int [players];
                        playersString = JOptionPane.showInputDialog(null, "How many players are going to take part?", "Players",
                             JOptionPane.WARNING_MESSAGE);
              players = Integer.parseInt(playersString);
              for(j = 0; j < ROUNDS; j++){
                   // generate a random number between 1 and 10
                   computersNumber = (int) (Math.random() * RANGE) + 1;
                   System.out.println(computersNumber);
              for(i = 0; i < MAX_GUESS; i++) {
                   userInput = JOptionPane.showInputDialog(null, "I am thinking of a number between 1 and 10 " +
                             "\n You have 3 attempt to guess what it is:",
                             "Guessing game", JOptionPane.INFORMATION_MESSAGE);
                   usersGuess = Integer.parseInt(userInput);
                                  boolean answer = checkAnswer(computersNumber, usersGuess);
                    giveHint(computersNumber, usersGuess);
                   if(answer == true) {
                        JOptionPane.showMessageDialog(null, win, "Result",
                                  JOptionPane.WARNING_MESSAGE);
                        winCount++;
                        System.out.println("Wins" + winCount);
                        break;
                   else if(answer == false) {
                        JOptionPane.showMessageDialog(null, lose, "Result",
                                  JOptionPane.ERROR_MESSAGE);
                        System.out.println(j);
                   if(i == 2){
                        JOptionPane.showMessageDialog(null, "Winning number was " + computersNumber,
                        "Guessing game", JOptionPane.INFORMATION_MESSAGE);
              JOptionPane.showMessageDialog(null, "Sorry you didn't win this time",
                        "Guessing game", JOptionPane.INFORMATION_MESSAGE);
              switch(winCount){
              case 1:
                   output = "Amateur";
                   break;
              case 2:
                   output = "Amateur";
                   break;
              case 3:
                   output = "Amateur";
                   break;
              case 4:
                   output = "Amateur";
                   break;
              case 5:
                   output = "Amateur";
                   break;
              case 6:
                   output = "Advanced";
                   break;
              case 7:
                   output = "Professional";
                   break;
              case 8:
                   output = "Champion";
                   break;
              default:
                   output = "Need more practice";
                   break;
              }// end switch statement
              // print message
              JOptionPane.showMessageDialog(null, output, "Check your grade",
                             JOptionPane.WARNING_MESSAGE);     
         public static boolean checkAnswer(int computersNumber, int usersGuess) {
              if(computersNumber == usersGuess) {
                   return true;
              } else {
                   return false;
              public static void giveHint(int computersNumber, int usersGuess) {
              if(usersGuess + 3 == computersNumber || usersGuess - 3 == computersNumber) {
                   JOptionPane.showMessageDialog(null, "Hint - your guess was cold",
                             "Guessing game", JOptionPane.INFORMATION_MESSAGE);
              } else if(usersGuess + 2 == computersNumber || usersGuess - 2 == computersNumber) {
                   JOptionPane.showMessageDialog(null, "Hint - your guess was warm",
                             "Guessing game", JOptionPane.INFORMATION_MESSAGE);
              } else if(usersGuess + 1 == computersNumber || usersGuess - 1 == computersNumber) {
                   JOptionPane.showMessageDialog(null, "Hint - your guess was hot",
                             "Guessing game", JOptionPane.INFORMATION_MESSAGE);
    }

    Since Java is an object oriented language you might want to create a Player class. Then think about how you can break things down and decide where certain methods go, in the Player class or the game class.
    As for determing the Player with the greatest wins, create another temp variable to hold the player with the most correct so far. Then you loop over all players and compare their wins with the temp variable. If it is greater swap them. a shortcut would be allocate player #1 to the temp variable then you only have to compare from player #2 onwards.

  • T400 - Accidentaly formatted the disk 1 (IMD-0) partition in disk management - Help Needed

    Hello,
    Initially when I re-formatted my computer to get rid of the factory image, I found that there was a hidden partition of 1.37GB which I could not touch, meaning i could not delete. I ignored it at that time and formatted my computer and reinstalled vista business on it using the license i got from lenovo. Now after some days, I was kind of getting concerned as to what exactly was the 1.37Gb partition on my computer. I guess I was getting worried as to why I was not able to reclaim that space for normal use. Today, I tried to reclaim it, by deleting the volume, thinking it should merge into the unallocated space, that I have on my primary hard drive. But it did not. However, what happened was that this space of 1.37GB did start showing up on My Computer, once I formatted it using NTFS. I then checked its properties in My Computer and it had an option of readyboost. I selected the option which says use this disk for readyboost, and immediately in no time, the disk was full with on 68MB remaining as free space. It also has an icon of readyboost in the drive, when I double-click it. This is when I figured that this space could be on a separate physical disk. I did some research and found out that this drive or device or chip, is listed as Disk-1 in disk management and as IMD-0 under Disk Drives in Device Manager. I googled about it, and found that it was related to the turbo memory. Now, I believe that turbo memory would be a separate flash chip, which would be hardwired to function in a particular way (enabling boosting speeds), and that it would be non-accessible to users from within windows for formatting or doing anything else. Hence, I also believe that the space which I reclaimed, is existing on my primary 320GB hard drive and is used in addition to the turbo memory, as a  cache, to boost speeds. However, since I do not understand the turbo memory concept very well, I would really appreciate if someone could explain how the turbo memory works, i.e. including IMD-0 and all that. And the main help I need is on how to hide the 1.37GB partition again, and put it in a format that it was earlier in, and usable for turbo memory. At present I do not know if it is being used by turbo memory or not, but below is the current status of the turbo memory:
    1. In Device manager, under disk drives, IMD-0 shows up, and in properties it just says device type -- disk drive. Now I read somewhere that it should say NVCACHE, but it does not say that on my pc, under any tabs of the properties of IMD-0. Can someone help me putting it back there.
    2. Under Disk Management, it says Local Disk H:, 1.37GB NTFS, Healthy (Active, Primary Partition). I don't exactly remember, but I guess prior to me formatting it, it said unallocated. Help needed here too.
    3. In the Turbo memory controller, it says Windows readyboot enabled, Windows Readydrive enabled, 2GB
    and below that I have checkboxes for enabling windows readyboost and readydrive checked.
    So guys, can please anyone help me in re-hiding the 1.37GB partition and making it in the state it was before.
    Thanks a lot for your help.

    Hi Eric,
    Please refer the following HP article to expand your array , refer the TechNet article to expand your drive:
    HP Proliant Servers - How to Expand an Array and Extend the Logical Drive
    http://h20566.www2.hp.com/portal/site/hpsc/template.PAGE/public/psi/mostViewedDisplay/?javax.portlet.begCacheTok=com.vignette.cachetoken&javax.portlet.endCacheTok=com.vignette.cachetoken&javax.portlet.prp_efb5c0793523e51970c8fa22b053ce01=wsrp-navigationalState%3DdocId%253Demr_na-c03510253-1%257CdocLocale%253Den_US&javax.portlet.tpst=efb5c0793523e51970c8fa22b053ce01&sp4ts.oid=4231377&ac.admitted=1411638027623.876444892.199480143
    TechNet article:
    Extend System/Boot Volume on Windows Server 2008/ Windows Vista/Win7 Beta
    http://blogs.technet.com/b/mghazai/archive/2009/02/24/extend-system-boot-volume-on-windows-server-2008-windows-vista-win7-beta.aspx
    Extend a simple or spanned volume
    http://technet.microsoft.com/en-us/library/cc776741.aspx
    I’m glad to be of help to you!
    *** This response contains a reference to a third party World Wide Web site. Microsoft is providing this information as a convenience to you. Microsoft does not control
    these sites and has not tested any software or information found on these sites; therefore, Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. There are inherent dangers in the
    use of any software found on the Internet, and Microsoft cautions you to make sure that you completely understand the risk before retrieving any software from the Internet. ***
    We
    are trying to better understand customer views on social support experience, so your participation in this
    interview project would be greatly appreciated if you have time.
    Thanks for helping make community forums a great place.

  • Arrays vs arraylists

    How do you guys determine whether to use arrays or the arrayList? I've seen situations where arrays are used that I thought arrayLists were more fitting. Is there some kind of performance penalty when using arrayLists over arrays?
    Thanks in advance!

    Array are more efficient rispect to ArrayList, but the dimension of an array can be decided only once:
    Array a = new Array[20] \\ this array will never contain 21 elements
    ArrayList are dinamically reallocated each time you add a new element
    Another thingh is thata when you istance a Array variable you will immediatly reserve a portion of memory for all the elements of the array
    When you istance a ArrayList variable you only create the variable but there will be memory allocation only for the inserted elements
    So:
    If you know in advance the max number of elements of the array probably you need an Array
    If you know the max number of element, this number if very hight, and you know that the max part of the program there will be very less element you probably will choose ArrayList to use less memory
    If you totally dont know how many elemnts you have to manipulate you have to chose an ArrayList.
    Hope it's enought (and not Wrong)
    Riccardo Coletta

Maybe you are looking for