nhập.
1.1 Chương trình
import java.io.*;
public class Matrix
{
public static void main(String[]args)
{
MT a=new MT(); MT b=new MT(); MT c= new MT();
System.out.print("\nNhap vao thong tin cho ma tran a:\n"); a.InputMT();
//a.OutputMT(a);
System.out.print("\nNhap vao thong tin cho ma tran b:\n"); b.InputMT();
//b.OutputMT(b);
System.out.print("\nTong cua 2 ma tran:\n"); c=c.Tong(a,b);
c.OutputMT(c);
System.out.print("\nHieu cua 2 ma tran:\n"); c=c.Hieu(a,b);
c.OutputMT(c);
System.out.print("\nTich cua 2 ma tran :\n"); c=c.Nhan(a,b);
c.OutputMT(c);
System.out.print("\nChia ma tran cho 1 so:\n"); c=c.Chia(a,b);
c.OutputMT(c); }
}
class MT{
private int sodong;
private int socot;
private float tri[][];
MT(){
this.socot=0;
this.sodong=0;
this.tri=new float[100][100]; } MT(int m,int n) { this.sodong=m; this.socot=n; }
public String NhapXau()
{
String s="";
DataInputStream temp=new DataInputStream(System.in);
try
{
s=temp.readLine();
}catch(IOException e){
Nguyễn Thanh Vũ – 10T2 – Nhóm 12A 91
return s;
}
public int getInt(String s)
{
return Integer.parseInt(s);
}
public void InputMT()
{
System.out.print("Nhap vao so dong cua ma tran:");
this.sodong=getInt(NhapXau());
System.out.print("Nhap vao so cot cua ma tran:");
this.socot=getInt(NhapXau());
System.out.print("Nhap vao gia tri cua ma tran:\n");
for( int i=0;i<sodong;i++)
for(int j=0;j<socot;j++) {
System.out.print("["+i+"]["+j+"]:="); tri[i][j]=getInt(NhapXau());
} }
public void OutputMT(MT t)
{
for(int i=0;i<t.sodong;i++) {
System.out.print("\n");
for(int j=0;j<t.socot;j++)
System.out.print(" "+t.tri[i][j]); }
}
public MT Tong(MT a,MT b)
{
MT c=new MT();
if(a.sodong!=b.sodong) {
System.out.print("Ban phai nhap vao 2 ma tran cung co thi moi cong duoc."); } else { c.sodong=a.sodong; c.socot=a.socot;
for( int i=0;i<a.sodong;i++)
for(int j=0;j<a.socot;j++) { c.tri[i][j]=a.tri[i][j]+b.tri[i][j]; } } return c; }
public MT Hieu(MT a,MT b)
{
MT c=new MT();
if(a.sodong!=b.sodong) {
System.out.print("Ban phai nhap vao 2 ma tran cung chieu thi moi cong duoc.");
else
{
c.sodong=a.sodong; c.socot=a.socot;
for( int i=0;i<a.sodong;i++)
for(int j=0;j<a.socot;j++) { c.tri[i][j]=a.tri[i][j]-b.tri[i][j]; } } return c; }
public MT Nhan(MT a,MT b)
{
MT c=new MT();
if(a.sodong!=b.socot){
System.out.print("So dong cua ma tran a phai bang so cot cua ma tran b.!");
}
else{
c.sodong=a.sodong; c.socot=b.socot;
for(int i=0;i<a.sodong;i++)
for(int j=0;j<b.socot;j++){ c.tri[i][j]=0;
for(int k=0;k<a.socot;k++) c.tri[i][j]=c.tri[i][j] + a.tri[i][k]*b.tri[k][j]; } } return c; }
public MT Chia(MT a,MT b)
{
MT c=new MT();
int k;
System.out.println("Nhap so de chia: "); k=getInt(NhapXau());
c.sodong=a.sodong; c.socot=b.socot;
for(int i=0;i<a.sodong;i++)
for(int j=0;j<b.socot;j++){ c.tri[i][j]=0; c.tri[i][j]=a.tri[i][j]/k; } return c; } }
Nguyễn Thanh Vũ – 10T2 – Nhóm 12A 93