Sunday, March 20, 2011

BlueJ menu driven program on matrix


import java.io.*;
class M
{
int i, j, k, l, m, n, o, option;
int mat1[][], mat2[][], mat3[][];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void take() throws Exception
{
System.out.println("Program for operations of matrix.\n\n");
System.out.println("First matrix--Enter number of rows : ");
k=Integer.parseInt(br.readLine());
System.out.println("Enter number of columns : ");
l=Integer.parseInt(br.readLine());
mat1=new int[k][l];
System.out.println("Second matrix--Enter number of rows : ");
m=Integer.parseInt(br.readLine());
System.out.println("Enter number of columns : ");
n=Integer.parseInt(br.readLine());

mat2=new int[m][n];
mat3=new int[k][n];
System.out.println("\nFirst matrix:");
for(i = 0; i< k; i++)
{
for(j = 0; j< l; j++)
{
System.out.println("\nEnter value:");
mat1[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("\nSecond matrix:");
for(i = 0; i< m; i++)
{
for(j = 0; j< n; j++)
{
System.out.println("\nEnter value:");
mat2[i][j]=Integer.parseInt(br.readLine());
}
}
choice();
}
private void choice()throws Exception
{
do
{
System.out.println("\nEnter your choice:");
System.out.print("0 for EXIt, 1 for Adition, 2 for Subtraction, 3 for  Multiplication");
System.out.println("\n\t\tEnter yout option : ");
option=Integer.parseInt(br.readLine());

if ((option >= 1) && (option < =3))
{
if (option == 1)
{
if ((k == m) && (l == n))
{
for(i = 0; i< k; i++)
{
for(j = 0; j< l; j++)
mat3[i][j] = mat1[i][j] + mat2[i][j];
}
}
else
{
System.out.println("\nSummation not possible\n");
return;
}
}
if (option == 2)
{
if ((k == m) && (l == n))
{
for(i = 0; i< k; i++)
{
for(j = 0; j< l; j++)
mat3[i][j] = mat1[i][j] - mat2[i][j];
}
}
else
{
System.out.println("\nSubtraction not possible\n");
return;
}
}
if (option == 3)
{
if (l == m)
{
for(i = 0; i< k; i++)
{
for(j = 0; j< n; j++)
{
mat3[i][j] = 0;
for(o = 0; o< m; o++)
mat3[i][j] = mat3[i][j] + mat1[i][o] * mat2[o][j];
}
}
}
else
{
System.out.println("\nMultiplication not possible\n");
return;
}
}
System.out.println("*** Matrix 1 ***\n");
for(i = 0; i< k; i++)
{
for(j = 0; j< l; j++)
System.out.print(" "+ mat1[i][j]);
System.out.println();
}
System.out.println("*** Matrix 2 ***\n");
for(i = 0; i< m; i++)
{
for(j = 0; j< n; j++)
System.out.print(" "+ mat2[i][j]);
System.out.println();
}
System.out.println("*** Result ***\n");
for(i = 0; i< k; i++)
{
for(j = 0; j< n; j++)
System.out.print(" "+ mat3[i][j]);
System.out.println();
}
}
}
while(option != 0);

}
public static void main(String args[]) throws Exception
{
 M ob=new M();
 ob.take();
 }
 }

Related Post: BlueJ Menu Based Programs

1 comment:

Subscribe via email

Enter your email address:

Delivered by FeedBurner