Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.mycompany.matrix;
- import com.mycompany.summatrixexception.*;
- import java.lang.String;
- import java.lang.StringBuffer;
- import mycompany.productmatrixexception.*;
- public class Matrix{
- protected int row = 0;
- protected int column = 0;
- protected int array[][];
- public Matrix (int row, int column){
- if(row < 0 || column < 0) throw new RuntimeException("Went beyond the matrix");
- this.row = row;
- this.column = column;
- if(row < 0 || column < 0) throw new RuntimeException("Went beyond the matrix");
- array = new int[row][];
- for (int i = 0; i < row; i++){
- array[i] = new int[column];
- }
- this.row = row;
- this.column = column;
- for (int i = 0; i<this.row; i++){
- for (int j = 0; j<this.column; j++){
- this.array[i][j] = 0 ;
- }
- }
- }
- public Matrix (){
- }
- public Matrix sum (Matrix a){
- Matrix c = new Matrix(this.row, this.column);
- if ((this.row != a.row) ||(this.column != a.column)) throw new SumMatrixException("Multiplication is impossible!");
- for (int i = 0; i<this.row; i++){
- for (int j = 0; j<this.column; j++){
- c.setElement(i,j,this.getElement(i,j)+a.getElement(i,j));
- // c.array[i][j] = this.array[i][j] + a.array[i][j];
- System.out.println( c.getElement(i,j));
- }
- }
- return c;
- }
- public Matrix product(Matrix a){
- Matrix c = new Matrix(this.row, this.column);
- if (this.column != a.row) throw new ProductMatrixException("Multiplication is impossible!");
- for(int i = 0; i < this.row; i++){
- for(int j = 0; j < a.column; j++){
- for(int k = 0; k < this.column; k++)
- c.setElement(i,j,c.getElement(i,j)+this.getElement(i,k)*a.getElement(k,j));
- //c.array[i][j] += (this.array[i][k] * a.array[k][j]);
- }
- }
- return c;
- }
- public void setElement(int row, int column, int value){
- if((row < 0 || column < 0) && (row > this.row)||(column > this.row)) throw new RuntimeException("Went beyond the matrix!");
- this.array[row][column] = value;
- }
- public int getElement(int row, int column){
- if((row < 0 || column < 0) && (row > this.row)||(column > this.row)) throw new RuntimeException("Went beyond the matrix!");
- return array[row][column];
- }
- public String toString(){
- StringBuffer strBuffer = new StringBuffer();
- for(int i = 0; i < this.row; i++){
- for(int j = 0; j < this.column; j++){
- strBuffer.append(this.getElement(i,j));
- strBuffer.append(" ");
- }
- strBuffer.append("\n");
- }
- return strBuffer.toString();
- }
- public boolean equals ( Object o ) {
- if(this.hashCode() != o.hashCode())
- return false;
- if ( o instanceof Matrix ) {
- Matrix a = (Matrix)o;
- if ((this.row != a.row) ||(this.column != a.column) ) {
- return false;
- }
- for (int i = 0; i<this.row; i++){
- for (int j = 0; j<this.column; j++){
- if (this.getElement(i,j) != a.getElement(i,j)){
- return false;
- }
- }
- }
- return true;
- }
- else
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment