不多说,1天时间看完数组之前内容,这就靠代码的实践总结一下吧~~

打印三角形

简单易懂,初学都会,就不注释了,前者为取巧的三角形实现方法,我注释了,直接上源码~~

public class Triangle {
    public void triangle(){
        /*for (int i = 0; i < 9; i++) {
            for (int j = 9; j > i; j--) {
                System.out.print(" ");
            }
            for (int j = 0; j < i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }*/
        for (int i = 0; i < 9; i++) {
            for (int j = 9; j > i; j--) {
                System.out.print("  ");
            }
            for (int j = 0; j < i; j++) {
                System.out.print("* ");
            }
            for (int j = i-1; j > 0; j--) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

打印九九乘法表

不多说,上代码~~

public class Multiplication {
    public void multiplication(){
        for (int i = 1; i <= 9; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(i+"*"+j+"="+i*j+"\t");
            }
            System.out.println();
        }
    }
}

将数组转化为稀疏数组,以及将稀疏数组转化为正常数组

public class SparseArray {
    public int[][] sparseArray(int[][] a){
        //记录有效数字,定义count变量记录
        int count=0;

        for (int i = 0; i < a.length ; i++) {
            for (int j = 0; j < a[i].length; j++) {
                if (a[i][j] != 0)
                    count++;
            }
        }
        //System.out.println(count);
        int[][] a2 = new int[count+1][3];
        a2[0][0] = a.length;
        a2[0][1] = a[0].length;
        a2[0][2] = count;
        //count变量此时计数用,重置为0
        count = 0;
        //遍历数组存储为稀疏数组
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                if (a[i][j] != 0)
                {
                    ++count;
                    a2[count][0] = i;
                    a2[count][1] = j;
                    a2[count][2] = a[i][j];
                }
            }
        }
        return a2;
    }
}

稀疏数组转化为正常数组

public class RestoreArrays {
    public int[][] restoreArrays(int[][] a){
        int[][] a2 = new int[a[0][0]][a[0][1]];
        for (int i = 1; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                a2[a[i][0]][a[i][1]] = a[i][j];
            }
        }
        return a2;
    }
}

以及打印输出二维数组

public class OutArrays {
    public void outArrays(int[][] a){
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                System.out.print(a[i][j]+"\t");
            }
            System.out.println();
        }
    }
}

实现的效果

图片

最后修改:2021 年 06 月 02 日
END
本文作者:
文章标题:JAVA学习基础汇总
本文地址:https://www.zaunekko.com/archives/5/
版权说明:若无注明,本文皆ZaunEkko原创,转载请保留文章出处。
如果觉得我的文章对你有用,请随意赞赏