Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

java - How to print two dimensional array of strings as String

I know how to do the toString method for one dimensional arrays of strings, but how do I print a two dimensional array? With 1D I do it this way:

public String toString() {
    StringBuffer result = new StringBuffer();
    res = this.magnitude;

    String separator = "";
    if (res.length > 0) {
        result.append(res[0]);
        for (int i=1; i<res.length; i++) {
            result.append(separator);
            result.append(res[i]);
        }
    }
return result.toString();

How can I print a 2D array?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The Arrays class defines a couple of useful methods

  • Arrays.toString - which doesn't work for nested arrays
  • Arrays.deepToString - which does exactly what you want

 

String[][] aastr = {{"hello", "world"},{"Goodbye", "planet"}};
System.out.println(Arrays.deepToString(aastr));

Gives

  [[hello, world], [Goodbye, planet]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...