nontoxicjon
nontoxicjon

Reputation: 153

Java two-dimensional array of chars

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;
    }
}

Upvotes: 1

Views: 12600

Answers (3)

T.Ho
T.Ho

Reputation: 1190

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.

Upvotes: 1

onof
onof

Reputation: 17367

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;
}

Upvotes: 2

Nurlan
Nurlan

Reputation: 673

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;
}

Upvotes: 0

Related Questions