Warning

 

Close

Confirm Action

Are you sure you wish to do this?

Confirm Cancel
BCM
Member Login

Posted: 9/8/2013 6:21:05 PM EDT
[Last Edit: 9/8/2013 6:22:22 PM EDT by DevilDog22]
How do I add to a two dimensional array. I know how to add to an array like this.

ArrayList<Integer> matrix = new ArrayList<>();

then I can add

matrix.add(value);

I am creating a matrix and this is my array

protected int [ ] [ ] matrix; How do I add to i later?

a user creates the matrix size

public void createMatrix (int value1, int value2) {
    this.row = value1;
    this.column = value2;
    matrix = new int [row] [column];
}

Now I want to be able to add a value to the matrix, say position (0,0) and I want to add the integer 4. Then I want to be able to move onto the next pos (0,1) and so on and so forth.
Link Posted: 9/8/2013 6:29:05 PM EDT
It should just be



matrix[0][0] = 4;


Link Posted: 9/8/2013 6:31:49 PM EDT
[Last Edit: 9/8/2013 6:33:04 PM EDT by Furloaf]
matrix[ 0 ] [ 0 ] = 4;

Generally:

array[ i ] [ j ] = x;

Without the spaces of course.

You also can not add new indices to a primitive array. You mentioned ArrayList first which does allow dynamically adding and removing indices.
Link Posted: 9/8/2013 6:47:51 PM EDT
[Last Edit: 9/8/2013 6:48:36 PM EDT by DevilDog22]
Discussion ForumsJump to Quoted PostQuote History
Originally Posted By Furloaf:
matrix[ 0 ] [ 0 ] = 4;

Generally:

array[ i ] [ j ] = x;

Without the spaces of course.

You also can not add new indices to a primitive array. You mentioned ArrayList first which does allow dynamically adding and removing indices.
View Quote



What I'm going for is to allow a user to input two number, those numbers be added together and stored in the position. I assume I have to continue to allow a user to input these numbers until the array is full.

Can I make an ArrayList two dimensional?
Link Posted: 9/8/2013 7:05:58 PM EDT
ArrayLists are single dimensional.

You're talking about two different types of objects. The arrays like foo[ x ] [ y ] are one type of object, addressed by the indices in square brackets. The array is allocated in a fixed size when you create it--you can't change the size once it's created.

ArrayLists are another type of object. They grow dynamcially as you add more objects. You use get() and add() to retrieve and add objects. You can also add objects of multiple types to an ArrayList, though that is not necessarily a good idea.

If you want to get tricky, define an object that has the two operands to the ArrayList, and then define a method that computes the result of addition.

class Foo
{
 int first;
 int second;

public Foo(first, second)
{ this. first = first;
 this.second = second;
}

public int getResult()
{
  return first + second;
}

}

Add that object to the arrayList.
Top Top