need help in java

Scorpy

Adept
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);
}}
 
I made changes .. using different variables still its happening .. I can search for element also display both arrays but not add and display or multiply and display D: .
 
import java.util.*;
import java.util.Scanner;
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[j]=o.nextInt();
}}}
public void display()
{
for(int i=0;i<a.length;i++) //replaced r with a.length coz r did not retain its value. u check y :)
{
for(int j=0;j<a.length;j++) //similarly with c :)
{
System.out.print(a[j]+"\t");
}
System.out.println();
}}}

class MatrixOp extends Matrix
{
int[][] add(MatrixOp m)
{
System.out.println(a.length);
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[j]=a[j]+m.a[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[j] += a[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[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);
}}


Solution! Search for comments in display function.
 
^^That code is not mine. I only identified the wrong part.
And please don't crape others thread just to increase ur post count :p. If u think the code is bad rectify first then blame others. I can bet u didn't even read the code; just glanced it. Anyway what is horrible just let me know. (only if u know:rofl:)Maybe it can help people who read this thread.
 
If you have taken offense of my comment, I apologize.

I meant code is horrible, didn't suggest it was your code which was horrible.

As you just identified the wrong part, perhaps you already know what's horrible in that code. If either you or somebody else really want to know what's wrong with the code, I might give some hints, on one condition that nobody would take any offense. :).
 
Dude u shouldn't mention such things. No offense taken now.

A starter can't write awesome codes immediately. It takes some time. Hope u understand what i'm trying to convey.
 
dude i made that a.length into r and c but still the same thing did any of you compile it ? ... also may I know whats so horrible in that code :p ... its for college practicals man ... anyways please tell me whats so horrible in it :p
 
of course i compiled it. And it executed properly also. It showed me the results of addition didn't check of multiplication though :p. Actually ur problem was identified that's y didn't go ahead.

And i'm very sure that u didn't compile the application again after making changes or made some mistake in the location stuff coz i ran the app myself before posting the code and it works 100%. :)
 
Every programmer is different, what's wrong fro me might not be, for you. Keep that in mind :).

Perhaps skeleton code was given to you be your teacher. Most issues lie with that. Anyway, assuming you have written all the code, I have following suggestions.

1) you need to understand what's an object and what's a class. Then understand 'type' and difference between 'type' and a 'class'. And connection between a 'type' and an 'interface'.

2) Always get your inheritance right. Otherwise you will be in serious trouble. Refere to C++ FAQ

3) UI or IO code must always be seperated off from your actual code. UI keeps changing remember that. You might think it's a small issue, but it doesn't take much time to get used to good practices.(In future you will know somthing called MVC, and this is what it advocates)

4) Don't create a variable unless required, limit it's scope.Don't 'reuse' a variable.(Refer to Bjarne's book)

5) Understand that your code would be far more comprehensible if you use functions aggressively.(Practice of programming-Kernighan)

6) Never write code in haste.(Bjarne stroustrup in his interviews)

None of these are my suggestions. Read Bjarne Stroustrup's interviews, faqs and his blog. You could read c++ faq by Mc Kleene.Most importantly as you are a java programmer "The Java programming language" by Arnold and James Gosling.

In this code you need an abstraction called Matrix. Matrix can have just one implementation, so you don't need an interface. If you think you need it, define matrix specific operations like add, multiply rather than read and display.Otherwise every interface would look the same :).

Your matrix class doesn't need o, r and c. They can be local variables. Minimize object state.Make readMatrix and displayMatrix external to the class as they involve IO/UI.

a.length is being used for both 'r' and 'c' unfortunately making it a square matrix. use a.length and a[0].length(making sure that a[0].length == a[1].length etc).Don't tell me you haven't written it, Whoever has written it, correcting that.

:). Anyway, I believe always try and use single dimensional array. It's private to you implementation, you could always do that.

You don't need MatrixOp. class is not a set of functions.. You don't need MatrixSearch too. And Neither MatrixOp nor MatrixSearch is 'a kind of' Matrix. So wrong use of inheritance. If you need create MatrixUtils something on the line of 'Collections' class in java std library.

add function should check if both matrices have the same dimensions. Early checking is better than late checking and is 'the java way'. Read Thinking in java by Bruce Eckel. If you don't agree, atleast resultant matrix cannot have a size of a.length X a.length. Might be a.length X a[0].length. But what if m.a has different dimensions? Similarly correct multiply.You know which matrices can and can't be multiplied, right?

Adding ints results in int, multiplying doubles result in double. It's better if matrices multiplied or added result in a matrix rather than an array.

Keep println nad nextInt out of search. Mixing IO code with your normal code isn't a nice idea.I prefer printf(available in java 5) if you need to print complex sentences. You can choose whatever you like, but make it readable.

You could and should avoid flag.

At last, do you really need to work so hard on IO? If that code exists just to test your operations, consider learning junit and using it with eclipse or netbeans. It isn't hard at all. Beginners get used to it pretty fast.

Please understand that I am just trying to help you learn better. I am myself still learning to program well and will perhaps remain that way. :)

I am on many programming forums most notably comp.lang.c++.moderated(for the past 10 years or so). You are generally encouraged to comment on code(for eg. 'this code is idiotic') and not on the person(like 'you are a bad programmer').(This will allow all programmers to learn by sharing each others experiences. All of us understand that expert programmers write pretty bad code sometimes and all of us were beginners at some point in time)

Wrote that comment on those lines. Hopefully you weren't offended.

Sanjeet Arora : Will definitely keep that in mind in future.

And these are just some of the issues :)
 
bleh dude :p .. i just started learning java and you bombarded me :p .... I know i didnt check dimensions but its ok and the college problem definition said to make an interface and make these read display methods and also create matrixop matrix search classes .... its all given in problem definition so I did it that way ... now one thing I ask from you ... can you write the same program in a professional way ? Im asking cos I need to see the difference ... Im using public or whatever anywhere lol so I need to see how ur program will look so if you have time please do .
 
Scorpy said:
bleh dude :p .. i just started learning java and you bombarded me :p .... I know i didnt check dimensions but its ok and the college problem definition said to make an interface and make these read display methods and also create matrixop matrix search classes .... its all given in problem definition so I did it that way ...
I know these teachers, mostly teach from "Balaguruswamy" or "Schildt" like books which does get you into the habit of putting getdata putdata kind of functions in every class :(. Anyway I just showed what's not correct, so that you atleast know there are a few issues. If you could suggest you, please get a better book and learn from that, forget about those ordinary teachers.

now one thing I ask from you ... can you write the same program in a professional way ? Im asking cos I need to see the difference ... Im using public or whatever anywhere lol so I need to see how ur program will look so if you have time please do .
Can I cheat?
Matrix.java

This seems a like a good implementation. except for show() and random() functions (which must be outside the class if they need to exist) and unnecessary introduction of A, B, M and N references. :eek:hyeah:
 
^the program killed me for sometime .... my code is nowhere near that :p .... I dunno when to use finally public and stuff .
 
Back
Top