简体   繁体   中英

printing a 2d object array with toString() method

I am trying to print out a 2d object array using the toString() method. i can display the array with a simple for loop but i want to use the toString() method. 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(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:

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. 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:

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. See example here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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