0

I am trying to convert this 2d char array to a String. The issue is it is outputting 100,000 characters even through the input array is no where near that. What is the correct way to convert a 2d char array to a string?

public String printMaze(char[][] maze) {
    String s= "";
    for(int i=0;i<maze.length;i++){
        for(int j=0; i<maze[i].length;j++){
            s= maze.toString();;
        }
    }
    return s;
}
6
  • 1
    provide sample input and output to make it more clear. Commented Apr 24, 2017 at 1:42
  • You are calling maze.toString(), how do you want to join the characters? Because you could do return Arrays.deepToString(maze); Commented Apr 24, 2017 at 1:42
  • It does not output any. The test server I used killed it once it hit 100k Commented Apr 24, 2017 at 1:44
  • stackoverflow.com/a/8995883/2308683 Commented Apr 24, 2017 at 1:44
  • It is supposed to return a String representation of the character array Commented Apr 24, 2017 at 1:45

2 Answers 2

3

Your inner loop has a problem and also I don't see you actually concetanting a string from the 2D character array. Here is the problem with the inner loop:

for (int j=0; i < maze[i].length; j++) {
        //   ^^^^ this will always be true for certain values of i
        // it should be j < maze[i].length
    s= maze.toString();;
}

In other words, your inner loop might be spinning forever, depending on the bounds of the maze. Instead, try the following code:

public String printMaze(char[][] maze) {
    String s = "";
    for (int i=0; i < maze.length; i++) {
        for (int j=0; j < maze[i].length; j++) {
            s += maze[i][j];
        }
        // uncomment next line if you want the maze to have rows
        // s += "\n";
    }
    return s.toString();
}

But as @ElliottFrisch mentioned, you could just return Arrays.deepToString(maze).

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

3 Comments

I'm assuming a maze should have rows, not one long string
why on earth can you not use StringBuilder ? It is a java.lang class
thank you. we can not use string builder because we have not gone over it yet
0

Hope this will help..

public String printMaze(char[][] maze) {
 String s= "";
 for(int i=0;i < maze.length;i++){
    for(int j=0; j < maze[i].length;j++){
        s = s + maze[i][j];
    }
 }
 return s;
}

4 Comments

giving me a array out of bound exception
please also explain what you have changed
Can you please tell me what is the length of your 2D array where you are getting exception. And if you have already modified your code then please ignore
Thanks for correcting. I haven't noticed when I was typing.

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.