简体   繁体   English

使用toString()方法打印2d对象数组

[英]printing a 2d object array with toString() method

I am trying to print out a 2d object array using the toString() method. 我正在尝试使用toString()方法打印出2d对象数组。 i can display the array with a simple for loop but i want to use the toString() method. 我可以使用简单的for循环显示数组,但我想使用toString()方法。 I'm new to programming so please bear with me. 我是编程新手,请耐心等待。

Basically i declared my array: 基本上我声明了我的数组:

          private Object [][]array;

and to print it out i used the for loop in the main method: 并打印出来,我在主要方法中使用了for循环:

  `  for(Object []a: data.array) //instantiated my class to data in main method
     {
        for(object k:a)
       {   
           System.out.println(k)
         }
          System.out.println();
      `

But i want to use the toString() method and be able to called it directly in the main method using: 但是我想使用toString()方法,并能够使用以下方法直接在main方法中调用它:

System.out.println(data);

How do i go about it? 我该怎么办? i am confused cause the toString() returns a string and i will have to override it. 我很困惑,因为toString()返回一个字符串,我将不得不覆盖它。 Do i have to cast? 我必须投吗? Please suggestions will help. 请建议会有所帮助。

My output from the for loop is below and would like the toString() to have a similar output: 我在for循环中的输出在下面,并且希望toString()具有类似的输出:

Country 1983 1984 1985 1986 1987 1988 1989 USA 0.1 0.2 0.4 0.5 0.6 0.8 0.1 MEXICO 0 1.3 1.23 0.4 0.1 0.0 0.2 Canada 1.3 2.1 0.3 0.1 0.0 1.1 1.1

what you're doing is the same as k.toString() (suggested by MadProgramme) if you wish to implement (better yet: override) your own toString then simply write a Class. 如果您希望实现(更好:重写)您自己的toString,则您要做的与k.toString() (由MadProgramme建议k.toString()相同。 See example here 在这里查看示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM