Scorpy
Contributor
well I wrote this program to add two array and multiply them but those 2 methods do not seem to work . no error is shown i just get the option to continue or not please if someone can spot a mistake do tell me i cannot spot any D: >>
Code:
import java.util.*;
interface Mat
{
void read();
void display();
}
class Matrix implements Mat
{
Scanner o=new Scanner(System.in);
int r,c;
int a[][];
public void read()
{
System.out.println("Enter no. of rows of array");
r=o.nextInt();
System.out.println("Enter no. of columns of array");
c=o.nextInt();
a=new int[r][c];
System.out.println("Enter elements of array");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
System.out.println("Enter element at position "+i+","+j);
a[i][j]=o.nextInt();
}}}
public void display()
{
for(int i=0;i<r;i++) {
for(int j=0;j<c;j++) {
System.out.print(a[i][j]+"\t");
}
System.out.println();
}}}
class MatrixOp extends Matrix
{
int[][] add(MatrixOp m)
{
int c[][]=new int[a.length][a.length];
for(int i=0;i<a.length;i++) {
for(int j=0;j<a.length;j++){
c[i][j]=a[i][j]+(int)m.a[i][j];
}}
return c;
}
int[][] mul(MatrixOp m) {
int m1cols=a.length;
int m2cols=(m.a).length;
int c[][]=new int[a.length][m2cols];
for (int i=0; i<a.length; i++)
for (int j=0; j<m2cols; j++)
for (int k=0; k<m1cols; k++)
c[i][j] += a[i][k]*m.a[k][j];
return c;}}
class MatrixSearch extends Matrix
{
void search ()
{
Scanner o=new Scanner(System.in);
System.out.println("Enter element to search.");
int ele=o.nextInt();
int flag=0;
int i,j=0;
loop1: for( i=0;i<a.length;i++){
for( j=0;j<a[0].length;j++){
if(a[i][j]==ele){
flag=1;
break loop1;
}}}
if(flag==0){
System.out.println("Element absent in array"); }
else{
System.out.println("Element present in array at position ("+i+","+j+")");}
}}
class MatrixMain
{
public static void main(String args[])
{
int c;
MatrixOp m1=new MatrixOp();
MatrixOp m2=new MatrixOp();
MatrixOp m3=new MatrixOp();
MatrixOp m4=new MatrixOp();
MatrixSearch s=new MatrixSearch();
Scanner o=new Scanner(System.in);
System.out.println("Enter details of array 1");
m1.read();
System.out.println("Enter details of array 2");
m2.read();
do{
System.out.println("Enter choice");
System.out.println("1.Add matrices\n2.Multiply matrices\n3.Search element in matrix\n4.Display");
c=o.nextInt();
switch(c)
{
case 1: m3.a=m1.add(m2);
m3.display();
break;
case 2: m4.a=m1.mul(m2);
m4.display();
break;
case 3: {System.out.println("Enter choice\n1.Seach in array 1\n2.Search in array2");
c=o.nextInt();
switch(c)
{
case 1: s.a=m1.a;
s.search();
break;
case 2: s.a=m2.a;
s.search();
break;
}}break;
case 4: System.out.println("Array 1 :");
m1.display();
System.out.println("Array 2 :");
m2.display();
break;
default : System.out.println("invalid choice");
}
System.out.println("Do you want to continue ?(0/1)");
c=o.nextInt();
}while(c==1);
}}