0

How can I add a 2d array into 1d array in java? Whenever I try to do that this message pops up:

Type Mismatch: cannot convert from char[][] to char

This is my code::

int numberOfCases = Integer.parseInt(scanner.nextLine());

char[] grids = new char[numberOfCases];

for(int i = 0; i < numberOfCases; i++) {
    while(scanner.hasNext()) {
        int gridDimensions = Integer.parseInt(scanner.nextLine());
        grids[i] = new char[gridDimensions][gridDimensions];

    }
}

Please help or give an alternative to what I am doing.

3
  • 1
    You are trying to add an two dimensional array to a char array. The char array can only contain chars. Otherwise you have to change that to char[][][] grids. Commented Nov 23, 2013 at 8:07
  • @Stephan can you tell me what's a 3d array? Commented Nov 23, 2013 at 8:10
  • 1
    If you already have 2d arrays and want to keep them in an array, it adds one dimension, so you need a 3d array. Commented Nov 23, 2013 at 8:12

2 Answers 2

3

Make your grids variable three-dimensional:

char[][][] grids = new char[numberOfCases][][];

Then, you should be able to add your two-dimensional array into this grids array.

Sign up to request clarification or add additional context in comments.

1 Comment

@MohammadAreebSiddiqui It works for me... all you need to do is modify the char[] grids line, nothing else.
1

You actually instantiate a new char[][] and trying to make it equal to char[]

   grids[i] = new char[gridDimensions][gridDimensions];

That's what is going wrong.

Try to loop over all values in the multidimensional array, and adding them one per one to a 1d array :)

2 Comments

I then will have problems in the next step of my logic.
@MohammadAreebSiddiqui Which is? I don't know any other way to add them than to loop over all of them. If you really want to have a 1d array. The three dimensional approach might work just as well though :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.