Assigning value to a two dimensional array

Hi,
I am trying to assign value to a two dimesional array the following way.
String [ ] [ ] d2D = new String [10] [ ];
for (int i = 0; i<obj.length; i++){
d2D = { "hello " + i, "here" , "we go" };
but it gives me the error "illegal start of expression " pointing to the line in the loop assigning values to d2D[i].
Any help would be deeply appreciated.

You need to use the syntax for creating an anonymous array: new String[] {..., ...}
String [ ] [ ] d2D = new String [10] [ ];
for (int i = 0; i<obj.length; i++){
    d2D[ i ] = new String[] { "hello " + i, "here" , "we go" };
}

Similar Messages

  • Count the number of values in a two dimensional array

    i am trying to figure out how to count the number of values in a two dimensional array.
    numScores = student[i][j].length;This doesn't work, i am trying to find a way of counting the columns

    Object[][] o;
    int tot = 0;
    for(int x = 0 ; x < o.length ; x++)
       tot += o[x].length;
    }If it's not a jagged array, however, this would be easier:
    int tot = o.length * o[0].length;

  • Assigning values to 2D Multi-Dimensional arrays ??

    How do I assign a value to a Multi-dimensional 2D Array,
    that has the righter array size omitted as it changes�.
    Code�
    SomeObj foobar = new SomeObj (first, second);
    SomeObj [ ] [ ] d2D = new SomeObj [10] [ ];
    d2D [0][0] = foobar;     //Causes a null pointer exception�
    NB: seems if I initiate �d2D = new SomeObj [10] [10];� with the righter array size initiated then the error doesn�t occur, but because of the nature of the data the size of each secondary array varies�
    Thx. Kharsim

    apparently not...
    from what i read up on Multi-Dimensional arrays, you only have to give a value to the leftest bracket...
    e.g.
    int [ 5 ] [     ] [     ] <~ Acceptable in Java
    int [ 5 ] [  6 ] [     ] <~ Acceptable in Java
    int [ 5 ] [  6 ] [ 24 ] <~ Acceptable in Java
    int [ 5 ] [     ] [ 24 ] <~ Not acceptable in Java
    so using arrays it should be possible to assign a value in either of the acceptable cases, but couldnt find a source that had such an example...

  • Assigning value to a two-dimensional byte array - problem or not?

    I am facing a really strange issue.
    I have a 2D byte array of 10 rows and a byte array of some audio bytes:
    byte[][] buf = new byte[10][];
    byte[] a = ~ some bytes read from an audio streamWhen I assign like this:
    for (int i=0; i<10; i++) {
        a = ~read some audio bytes // this method properly returns a byte[]
        buf[i] = a;
    }the assignment is not working!!!
    If I use this:
    for (int i=0; i<10; i++) {
        a = ~read some audio bytes
        for (int j=0; j<a.length; j++) {
            buf[i][j] = a[j];
    }or this:
    for (int i=0; i<10; i++) {
        System.arraycopy(a, 0, buf, 0, a.length);
    }everything works fine, which is really odd!!
    I use this type of value assignment for the first time in byte arrays.
    However, I never had the same problem with integers, where the problem does not appear:int[] a = new int[] {1, 2, 3, 4, 5};
    int[][] b = new int[3][5];
    for (int i=0; i<3; i++) {
    b[i] = a;
    // This works fineAnybody has a clue about what's happening?
    Is it a Java issue or a programmers mistake?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Back again! I'm trying to track down the problem.
    Here is most of my actual code to get a better idea.
    private void test() {
         byte[][] buf1 = new byte[11][];
         byte[][] buf2 = new byte[11][];
         AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(audioFile);
         byte[] audioBytes = new byte[100];
         int serialNumber = 0;
         while (audioInputStream.read(audioBytes) != -1) {
              if (serialNumber == 10) {
                   serialNumber = 0; // breakpoint here for debugging
              // Fill buf1 -- working
              for (int i=0; i<audioBytes.length; i++) {
                   buf1[serialNumber] = audioBytes[i];
              // Fill buf2 -- not working
              buf2[serialNumber] = new byte[audioBytes.length];
              buf2[serialNumber] = audioBytes;
              serialNumber++;
    }I debugged the program, using a debug point after taking 10 "groups" of byte arrays (audioBytes) from the audio file.
    The result (as also indicated later by the audio output) is this:
    At the debug point the values of buf1's elements change in every loop, while buf2's remain unchanged, always having the initial value of audioBytes!
    It's really strange and annoying. These are the debugging results for the  [first|http://eevoskos.googlepages.com/loop1.jpg] ,  [second|http://eevoskos.googlepages.com/loop2.jpg]  and  [third|http://eevoskos.googlepages.com/loop3.jpg]  loop.
    I really can't see any mistake in the code.
    Could it be a Netbeans 6.1 bug or something?
    The problem appears both with jdk 5 or 6.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Assigning two dimensional array to each other

    Hi All,
    I have two two-dimensional arrays and I want to assign one's second dimension's values as the other's second dimension's values in this way:
            int userCounter = 0;
            for (int userID : mostCommonUsers) {
                reducedTrainingVectorForSimilarity[userCounter] = trainingVectorForSimilarity[userID];
                userCounter++;
            }In the above code, I have an *"ArrayList<Integer> mostCommonUsers"*, and iterate through this. I'm using the values inside this array list, as a first dimension's index number of the *"trainingVectorForSimilarity"*, and assigning all the values in the second dimension to the left-hand-side array's second dimension. Both array has fixed length of second dimension. So, am I right by doing this, or I should make a for-loop to iterate over the individual values on the second dimensions of both arrays?
    Another similar question: In the below code, *"trainingVectorForSimilarity"* is an *"float[][]"*, so basically I assign all the second dimensions' values into a newly created array named *"trainingUserRatings"*. Again, I assumed that if the corresponding first dimesion's second dimension values will be assign without any iteration over each values.
    for (int i = 0; i < trainingVectorForSimilarity.length; i++) {
                float[] trainingUserRatings = trainingVectorForSimilarity;
    similarity[i] = calculateCosineSimilarity(testingVectorForSimilarity, trainingUserRatings);
    Am I right for both cases?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Here is the output for the code that you sent:
    [[1, 2, 3], [4, 5, 6]]
    [[1, 2, 3], [4, 5, 6]]
    [[1, 2, 3], [4, 5, 6]]
    [[1, 2, 3], [4, 5, 6]]
    [[1, 2, 3], [4, 999999, 6]]
    [[1, 2, 3], [4, 999999, 6]]
    [[1, 2, 3], [4, 999999, 6]]
    [[1, 2, 3], [4, 5, 6]]
    [null, [4, 999999, 6]]
    [null, [4, 999999, 6]]
    [[1, 2, 3], [4, 999999, 6]]
    [[1, 2, 3], [4, 5, 6]]I confused that even making an array copy still refers the same object but not a copy of that object. For example:
    float[][] trainingVectorForSimilarity is defined and initialized.
                float[] trainingUserRatings = new float[trainingVectorForSimilarity.length];
    trainingUserRatings = trainingVectorForSimilarity[i];
    is the same withfloat[] trainingUserRatings = new float[trainingVectorForSimilarity[i].length];
    System.arraycopy(trainingVectorForSimilarity[i], 0, trainingUserRatings, 0, trainingUserRatings.length);

  • Creating a Two Dimensional Array in Xcode and populating it with a values f

    Whats the easiest way to declare a two dimensional array in Xcode. I am reading an matrix of numbers from a text file from a website and want to take the data and place it into a 3x3 matrix.
    Once I read the URL into a string, I create an NSArray and use the componentsSeparatedByString method to strip of the carriage return line feed and create each individual row. I then get the count of the number of lines in the new array to get the individual values at each row. This will give mw an array with a string of characters, not a row of three individual values. I just need to be able to take these values and create a two dimensional array.

    I'm afraid you are in the wrong place. Look here for the last two forums on programming. However, XCode support is mostly found at developer.apple.com. You can access their forums by registering. Registration is free.

  • How to get number of rows and columns in a two dimensional array ?

    Hello,
    What would be the simplest way to get number of rows and columns in a two dimensional array represented as integers ?
    I'm looking for another solution as For...Each loop in case of large arrays.
    Regards,
    Petri

    Hi Petri,
    See a attached txt file for obtaining two arrays with upper and lower index values
    Regards
    Ray
    Regards
    Ray Farmer
    Attachments:
    Get2DArrayIndex.txt ‏2 KB

  • Set number of elements in a two dimensional array

    Hi,
    Does anyone know how to set the number of elements in a two dimensional array directly in teststand.
    To set a one dimsional array is simple:
    SetNumElements( locals.somearray,4)
    Is there a method to do this for a two dimensional array?
    Sean

    From the help file (TestStand 4.2.0):
    PropertyObject.SetNumElements
    SetNumElements Method
    Syntax
    PropertyObject.SetNumElements ( numElements, options = 0)
    Purpose
    Sets the number of elements of a single dimensional array.
    Remarks
    This method is only valid for single dimensional arrays. The elements in the array retain their values. Use the PropertyObjectType.ArrayDimensions property to set the number of elements in each dimension of a multi-dimensional array.
    Parameters
    numElements As Long
    [In] New number of elements for the array.
    options As Long
    [In] Pass 0 to specify the default behavior, or pass one or more PropertyOptions constants. Use the bitwise-OR operator to specify multiple options.
    This parameter has a default value of 0.
    So you could use, for example: Locals.MultidimensionalArray.Type.ArrayDimensions.SetBounds({1,0},{3,4}) to set an array to have three dimensions (1,2,3), each with five elements (0,1,2,3,4).

  • How can I do two dimensional arrays?

    I am a C++ programmer and in C++ I am able make a two dimensional array and input the values that correspond to those cells.
    After I saw the proposals that you (experts) made I am going to share a little of the classified information that I was working for the undefeatable XO game.
    First step:My idea was to make a two dimensional array(in C++ we use the following syntex for two dimensional array{array[i][j]})
    I was wondering if I am able to make a two dimensional array using LABVIEW .
    Second step: Store the values of X or O inside the 2D array.And use maybe boolean variables(in C++ we use inaddition to that if statement).
    My second question :What can I do inorder to minimize the number of boolean vaariables?(also if statements in C++)
    Jupiter
    extinct when hell froze over

    This is a subroutine I use to check for a winner in a XO game.
    While playing, the main code replaces default 0's by 1's inside the 2D array of a single player.
    Then the main code calls this VI with the 2D array of that player and check for a winning game.
    Any board size is ok as long as you have equal number of cols & rows.
    So, enter 1's at any location in the "Score" 2D array and the code will check for a winning game.
    As you can see I don't use any boolean variables, except the return value of this VI (read function) 
    So to answer your second question; I minimized the use of boolean variables to 0 1! Is that ok for you?
    Attachments:
    TTT-Check4Winner.vi ‏20 KB

  • How to change the value of a two dimensional vector

    hi,
    I have a two dimensional array, Vector<Vector> myData, which contains strings. It's size is 5 rows and 6 columns
    I would like to change the value of, say, row 3, colum 5 from whatever it contains now to "new data"? I have searched and searched, but no luck
    thanks

    micheleg wrote:
    hi,
    I have a two dimensional array, Vector<Vector> myData, which contains strings. It's size is 5 rows and 6 columns
    I would like to change the value of, say, row 3, colum 5 from whatever it contains now to "new data"? I have searched and searched, but no luck
    thanksFirst off, you do not have an array of any dimension.You have a Vector that contains Vectors that contain Objects (you should provide a more specific type in your declaration).
    To change the element at position x in the y'th Vector, get the y'th Vector and change the x'th element in said Vector.
    As a side note, you should be using ArrayList instead of Vector these days.

  • Two dimensional arrays?

    how do you display a two dimensional array in jsf? my current code is this
    <t:dataTable value="#{bean.rows}" var="row">
    <t:columns value="#{row.columns}" var="column">
    <f:facet name="header">
    <h:outputText value="#{column.name}" />
    </f:facet>
    <h:outputText value="#{column.value}" />
    </t:columns>
    </t:dataTable>am using myfaces tomhawk, thanks!! :)

    You can use getters/setters as deep as you want.value="#{row.column.name}"is valid.

  • Return a two dimensional array

    Hi,
    I'm probably doing this wrong from the start, but I have an two dimensional array with only integers. These are the result of some mathematical calculations (aren't they always? :-) ) and I need to use those in another class. So I placed this array in a Vector and used this as a return value.
    It looks like this:
    final int[][] somArray = new int[aantalSommen][3];
    Vector maalSommen= new Vector();
    somArray[counter][0] =A;
    somArray[counter][1] =B;
    maalSommen.add(somArray[counter]);
    return maalSommen;So now I have this array into a vector, I can't get the values out.
    in the code below Vector sommen is the vector containing the array.
    for (int i =0;i<sommen.size(); i++ ) {
      int [][] som=(int[][]) sommen.elementAt(i);
    }The above code is not working.It gives me a cast error..

    ok, this is my attempt for the sscce...
    This class generates the results I need..
    public Vector MaalSommen(int aantalSommen, int[] TafelReeks) {
              final Vector maalSommen = new Vector();
              final int[][] somArray = new int[aantalSommen][3];
              boolean dupesCheck=false;
              int A = 1;
              int B=1;
              for (int counter=0; counter<aantalSommen; counter++) {
                   A=generator.nextInt(10);
                   B=randomizeArray(TafelReeks);
                   // check for dupes..
                   while ( ! dupesCheck) {
                        if (!( dupesCheck=checkDupes(A,B, counter,somArray))) {
                             A=generator.nextInt(10);
                             B=randomizeArray(TafelReeks);
                   dupesCheck=false;// reset the checker
                   somArray[counter][0] =A;
                   somArray[counter][1] =B;
                   somArray[counter][2] =somArray[counter][0]* somArray[counter][1];
                       maalSommen.add(somArray[counter]);
              return maalSommen;
         }What I think is happening is I put the array into the vector..But it turn out this is not the case..

  • How to copy data in text file into two-dimensional arrays?

    Greeting. Can somebody teach me how to copy the input file into two-dimensional arrays? I'm stuck in making a matrix with number ROWS and COLUMNS according to the data in "input.txt"
    import java.io.*;
    import java.util.*;
    public class array
        public static void main (String[] args) throws FileNotFoundException
        { Scanner sc = new Scanner (new FileReader("input.txt"));
            PrintWriter outfile = new PrintWriter("output.txt");
        int[][]matrix = new int[ROWS][COLUMNS];
    }my input.txt :
    a,b,c
    2,2,1
    1,1,1
    2,2,1
    3,3,1
    4,4,1
    5,5,1
    1,6,2
    2,7,2
    3,8,2
    4,9,2
    5,10,2

    import java.io.*;
    import java.util.*;
    public class array {
        public static void main(String[] args) throws IOException {
            FileInputStream in = null;
            FileOutputStream out = null;
    try {
        in = new FileInputStream("input.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = null;
        while ((line = reader.readLine()) != null) {
            String split[]=line.split(",");
    catch (IOException x) {
        System.err.println(x);
    } finally {
        if (in != null) in.close();
    }}}What after this?

  • How to use two dimensional array in custom.pll

    HI
    How to use two dimensional arrays in custom.pll
    I tried by the following way .
    type ship_array is table of number index by binary_integer;
    type vc_array is table of ship_array index by binary_integer;
    But I am getting the error as that
    A plsql table may not contain a table or a record with composite fields.
    Please tell me the way how to use them

    which forms version are you using? two dimensional arrays are available in >= 9i if memory serves.
    regards

  • Variable number of two dimensional arrays into one big array

    I have a variable number of two dimensional arrays.
    The first dimension is variable, the second dimension is always 7.
    i.e.:
    Object[][] array0 = {
    {"tim", "sanchez", 34, 175.5, "bla", "blub", "[email protected]"},
    {"alice", "smith", 42, 160.0, "la", "bub", "[email protected]"},
    Object[][] array1 = {
    {"john", "sdfs", 34, 15.5, "a", "bl", "[email protected]"},
    {"joe", "smith", 42, 16.0, "a", "bub", "[email protected]"},
    Object[][] arrayi = ...I'm generating these arrays with a for-loop:
         for (int i = 0; i < filter.length; i++) {
              MyClass c = new MyClass(filter);
              //data = c.getData();
    Where "filter" is another array which is filled with information that tells "MyClass" how to fill the arrays.
    "getData()" gives back one of the i number of arrays.
    Now I just need to have everything in one big two dimensional array.
    i.e.:Object[][] arrayComplete = {
    {"tim", "sanchez", 34, 175.5, "bla", "blub", "[email protected]"},
    {"alice", "smith", 42, 160.0, "la", "bub", "[email protected]"},
    {"john", "sdfs", 34, 15.5, "a", "bl", "[email protected]"},
    {"joe", "smith", 42, 16.0, "a", "bub", "[email protected]"},
    Any idea on how to accomplish this? It's blowing my mind right now.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Just brainstorming here:
    Why not put your actual data in a class and store that in a LinkedList (so you know the total number of elements for your multi-dimensional array). Then initalize your multi-dimensional array and populate it? Haven't tested the following, but thinking something along the lines of
    public class MyData {
         //data here
         public Object[] toArray() {
              //something similar to this
              return new Object[] = {"tim", "sanchez", 34, 175.5, "bla", "blub", "[email protected]"};
    LinkedList<MyData> data = new LinkedList<MyData>();
    data.add(mydata1);
    //however many times you need
    Object[][] arrayComplete = new Object[data.size()][7];
    for(int i = 0; i < data.size(); i++) {
         arrayComplete[i] = data.removeFirst().toArray();
    }Another option for knowing how many rows you would need might be using something like:
    int rows = 0;
    rows += array1.length;
    rows += array2.length;
    //etc...But is not entirely useful if you don't know how many variable arrays you have (although reflections might help if the name of the array variable is incremented systematically, someone told me earlier to avoid reflections since it could make debugging a LOT more difficult).
    Edited by: bogdana on Apr 1, 2010 10:38 AM

Maybe you are looking for