1

I need to write a java program that has an array-returning method that takes a two-dimensional array of chars as a parameter and returns a single-dimensional array of Strings. Here's what I have

import java.util.Scanner;
public class TwoDimArray {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("Enter the number of Rows?");
        int rows = s.nextInt();
        System.out.println("Enter the number of Colums?");
        int cols = s.nextInt();
        int [][] array = new int [rows] [cols];
    }

    public static char[ ] toCharArray(String token) {
        char[ ] NowString = new char[token.length( )];
        for (int i = 0; i < token.length( ); i++) {
            NowString[i] = token.charAt(i);
        }
        return NowString;
    }
}
0

3 Answers 3

2

You need an array of String, not of chars:

public static String[] ToStringArray(int[][] array) {
    String[] ret = new String[array.length]; 

    for (int i = 0; i < array.length; i++) {
       ret[i] = "";
       for(int j = 0; j < array[i].length; j++) {
          ret[i] += array[i][j];
       }

    }
    return ret;
}
Sign up to request clarification or add additional context in comments.

Comments

1

The above answers are right; however you may want to use StringBuilder class to build the string rather than using "+=" to concatenate each char in the char array.

Using "+=" is inefficient because string are immutable type in java, so every time you append a character, it will have to create a new copy of the string with the one character appended to the end. This becomes very inefficient if you are appending a long array of char.

1 Comment

+1 you're right, but I chose the easier way, given the level of expertise of the OP
0
public String[] twoDArrayToCharArray(char[][] charArray) {
    String[] str = new String[charArray.length];
    for(int i = 0; i < charArray.length; i++){
        String temp = "";
        for(int j = 0; j < charArray[i].length; j++){
            temp += charArray[i][j];
        }
        str[i] = temp;
    }
    return str;
}

Comments

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.