簡體   English   中英

我的簡單數組程序未提供預期的輸出

[英]My simple array program not giving the expected output

我寫了一個簡單的數組,存儲3x3矩陣。 但是,當我運行代碼時,它不會給出3x3矩陣。 只給出一列作為輸出。

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();

            }
        }
    }
}

輸出是這樣的

0

1

2

3

4

6

7

8

只需為每行打印一行。 像這樣 :

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

為了改善您的代碼,您還可以像下面這樣更改for循環:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM