Java编写一个程序实现矩阵的运算加减乘除,(并对其中的异常进行处理)

如题所述


/**
 * 矩阵:由 m × n 个数Aij排成的m行n列的数表称为m行n列的矩阵,简称m × n矩阵
 * 说白了就是一个二维数组,下面的程序用整形作为数据类型,其他类型运算大同小异
 * 
 */

public class MatrixUtils {

    /**
     * 矩阵运算:加(减法与之类似)
     */
    public static int[][] matrixAdd(int[][] addend, int[][] summand) {
        if (addend == null || addend.length == 0) {
            throw new IllegalArgumentException("addend matrix is empty!");
        }
        if (summand == null || summand.length == 0) {
            throw new IllegalArgumentException("summand matrix is empty!");
        }
        //矩阵加减要求两个矩阵类型一致,即行列数相同
        int row = addend.length;
        int col = addend[0].length;
        if (row != summand.length || col != summand[0].length) {
            throw new IllegalArgumentException("summand and summand not the same type!");
        }
        int[][] sum = new int[row][col];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                sum[i][j] = addend[i][j] + summand[i][j];
                // sum[i][j] = addend[i][j] - summand[i][j]; //减法
            }
        }
        return sum;
    }

    /**
     * 矩阵运算:乘法,没找到除法的运算规则
     */
    public static int[][] matrixMultiply(int[][] addend, int[][] summand) {
        if (addend == null || addend.length == 0) {
            throw new IllegalArgumentException("addend matrix is empty!");
        }
        if (summand == null || summand.length == 0) {
            throw new IllegalArgumentException("summand matrix is empty!");
        }
        //两个矩阵的乘法仅当第一个矩阵A的列数和另一个矩阵B的行数相等时才能定义。如A是m×n矩阵和B是n×p矩阵,它们的乘积C是一个m×p矩阵 
        int row = addend.length;
        int col = summand[0].length;
        if (addend[0].length != summand.length) {
            throw new IllegalArgumentException("summand and summand not the same type!");
        } 
        int[][] sum = new int[row][col];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                for (int z = 0; z < addend[0].length; z++) {
                    sum[i][j] += addend[i][z] * summand[z][j];
                    System.out.println("sum[" + i+  "]["+ j+"]= " + sum[i][j]);
                }
            }
        }
        return sum;
    }
}

追问

感谢 请问你还能帮我编写两个代码图题么?我增加财富奖励值,都给你。因为是文科生,选修的Java,实在是不会。并非贪玩好耍之辈,谢啦

你想要多少财富值 我都可以给你 大神 谢啦

追答/**
     * 只能对字符不重复的字符串进行判读,字符重复则不行,如:aacc 和 accc程序也会判断为真
     * 
     * @param s1
     * @param s2
     * @return
     */
    public static boolean isTwins(String s1, String s2) {
        if(s1 == null || s2 == null){
            throw new IllegalArgumentException("空字符串无法判断");
        }
        if(s1.length() != s2.length()){
            return false;
        }
        for(int i = 0;i< s1.length(); i++){
            if(s2.indexOf(s1.charAt(i)) < 0){
                return false;
            }
        }
        return true;
    }

GUI编程很麻烦,代码量有点多,就不做了。

追问

你要多少财富值呀 我提高悬赏 然后给你吧

知道你不容易 感谢啦

追答

你随意吧!

追问

它一次提高悬赏最多50 所以给你80啦 谢了

温馨提示:答案为网友推荐,仅供参考
相似回答