简体   繁体   中英

My simple array program not giving the expected output

I wrote a simple array which I store 3x3 matrix. But when I run the code it doesn't give 3x3 matrix. just gives a single column as output.

class sucks
{

    public static void main(String[] args)
    {

        int g[][]=new int[3][3];

        int h,k,l=0;

        for(k=0;k<3;k++)
        {
            for(h=0;h<3;h++)
            {

                g[k][h]=l;
                l++;

            }
        }

        for(k=0;k<3;k++)
        {
            for(h=0;h<3;h++)
            {

                System.out.print(g[k][h]+" ");
                System.out.println();

            }
        }
    }
}

The out put is like this

0

1

2

3

4

5

6

7

8

Just print a new line for each row. Like this :

for(k=0;k<3;k++){
    for(h=0;h<3;h++){    
       System.out.print(g[k][h]+" ");    
    }
    System.out.println();
}

To improve your code, you could also change your for loops like this :

for(k=0;k<g.length;k++){
    for(h=0;h<g[k].length;h++){ 

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