Saturday, 25 February 2017

Generic Array2D


public class Array2D <T>{
protected int trows;
protected int tcols;
protected T[] elements;


@SuppressWarnings("unchecked")
public Array2D( int rows, int cols )
{

if( rows<1 || cols<1 )
throw new IllegalArgumentException ("initialCapacity must be >= 1");

elements =(T[]) new Object[rows*cols];
trows = rows;
tcols = cols;
}

public Array2D()
{
trows = tcols = 0;
}

@SuppressWarnings("unchecked")
public void create( int rows, int cols )
{
if( rows<1 || cols<1 )
throw new IllegalArgumentException ("initialCapacity must be >= 1");

elements = (T[]) new Object[rows*cols];
trows = rows;
tcols = cols;
}

void checkIndex(int row, int col)
{
if( row < 0 || row>=trows || col < 0 || col>=tcols )
throw new IndexOutOfBoundsException ("Row: "+ row + ", Range: 0 - "+trows+"Col: "+ col + ", Range: 0 - "+tcols);
}

public void put( int row, int col, T theElement )
{
checkIndex(row, col);

elements[row*tcols+col] = theElement;
return;
}

public T get( int row, int col )
{
checkIndex(row, col);
return
(T)elements[row*tcols+col];
}


public Object remove( int row, int col )
{
checkIndex(row, col);

Object ob = elements[row*tcols+col];
elements[row*tcols+col] = null;

return ob;
}

public int nrows()
{
return trows;
}

public int ncols()
{
return tcols;
}

public String toString()
{
StringBuffer s = new StringBuffer("[");

for (int r=0; r<trows; r++) {
for (int c=0; c<tcols; c++) {
if(elements[r*tcols+c] ==null)
s.append("_, ");
else s.append(elements[r*tcols+c].toString() + ", ");
}

s.delete(s.length() -2, s.length());
s.append(" # ");
}

if(trows>0 && tcols>0)
s.delete(s.length() -2, s.length());

s.append("]");
return new String(s);
}
}

import java.util.Scanner;

public class Runner {
public static void main(String[] args) {
int i, j;

int tRows;
int tCols;

Array2D<Double> Ob1;
Array2D<Double> Ob2;
Array2D<Double> Ob3;

Scanner s = new Scanner(System.in);

System.out.print("Rows   : "); tRows = s.nextInt();
System.out.print("Columns: "); tCols = s.nextInt();

Ob1=new Array2D<Double>( tRows, tCols );
Ob2=new Array2D<Double>( tRows, tCols );
Ob3=new Array2D<Double>( tRows, tCols );

System.out.println( "--------------------" );
System.out.println( "Enter values for first matrix" );

for( i=0 ; i<tRows ; i++ )
{
for( j=0 ; j<tCols ; j++ )
{
Ob1.put( i, j,  s.nextDouble() );
}
}

System.out.println("--------------------");
System.out.println( "Enter values for second matrix" );

for( i=0 ; i<tRows ; i++ )
{
for( j=0 ; j<tCols ; j++ )
{
Ob2.put( i, j,  s.nextDouble() );
}
}

for( i=0 ; i<tRows ; i++ )
{
for( j=0 ; j<tCols ; j++ )
{
Ob3.put( i, j, Ob1.get(i,j)+ Ob2.get(i,j) );
}
}


System.out.println("---Results----");

for( i=0 ; i<tRows ; i++ )
{
for( j=0 ; j<tCols ; j++ )
{
System.out.print( Ob3.get(i,j)+"\t" );
}
System.out.println();
}

s.close();
}
}

No comments:

Post a Comment