[Java] Appending data into arrays

Discussion in 'Off Topic' started by brncao, Oct 10, 2011.

Thread Status:
Not open for further replies.
  1. brncao

    brncao Notebook Evangelist

    Reputations:
    541
    Messages:
    570
    Likes Received:
    5
    Trophy Points:
    31
    Does anyone know how to append data into an array of size 100? There are 3 arrays. I'm using a switch statement so whenever a user selects 1, it prompts the user for input. It takes 3 different values (a string, double, and int), but now I want it to be appended into the array respectively, not overwrite it. All I could do is force the user to fill up 100 elements, but that's not good hehe.
     
  2. Thaenatos

    Thaenatos Zero Cool

    Reputations:
    1,581
    Messages:
    5,345
    Likes Received:
    120
    Trophy Points:
    231
    Do you mean append data in each element? or add elements?

    If the latter is what youre looking for java cannot do dynamic arrays and youll have to work some pointer magic in c++ to do so.

    if appending to data in an element then adding the Int elements like so(same goes for double primatives):

    Code:
    anArray[count] += anArray[count];
    
    As for strings the following might work for you:

    Code:
    anArray[count] = anArray[count].concat(anotherArray[count]);
    
     
  3. redrazor11

    redrazor11 Formerly waterwizard11

    Reputations:
    771
    Messages:
    1,315
    Likes Received:
    0
    Trophy Points:
    55
    Not quite sure I understand what you mean by "appended into the array respectively".

    You could run through a loop saying : "Please enter the next element" in which it would increment the index of the array and store their entry, and then ask again (until reaching 100). This would keep indexing and adding to the array, and not overwrite the first entry.

    Or, if you mean starting over...you could store the data in a text file, read into the array on start, and save back to the text file after user finishes entering the data they have.

    Then they could pickup where they left off at next runtime.
     
  4. Simplified

    Simplified The Most Awesome

    Reputations:
    428
    Messages:
    766
    Likes Received:
    0
    Trophy Points:
    30
    Use an ArrayList instead.

    An example:
    //main method
    //omissions
    ArrayList< DataUnit > list = new Arraylist< DataUnit >();
    //append data from user input by writing your own code under this row
    //end of main method

    Public interface DataUnit{
    dataUnit(String s, Double d, int i);
    toString();
    getDouble();
    getInt();
    }
     
Thread Status:
Not open for further replies.

Share This Page