Matrix

 

public class Matrix
{
// Attribute
float Elemente[][];
int ZeilenZahl, SpaltenZahl;
// Konstruktor
public Matrix(int Zeilen, int Spalten)
{
Elemente = new float[Zeilen][Spalten];
ZeilenZahl = Zeilen;
SpaltenZahl = Spalten;
}
//
// Zugriffsoperationen
//
public int getSpaltenZahl()
{
return SpaltenZahl;
}

public int getZeilenZahl()
{
return ZeilenZahl;
}

public float getElement(int zeile, int spalte)
{
return Elemente[zeile][spalte];
}

public void setElement(int zeile, int spalte, float wert)
{
Elemente[zeile][spalte] = wert;
}
//
// Rueckgabewert = diese Matrix + eineMatrix
//
public Matrix addiere(Matrix eineMatrix)
{
// Voraussetzung: Groesse dieser Matrix = Groesse von >eineMatrix<
if( (eineMatrix.getZeilenZahl() == ZeilenZahl)
&& (eineMatrix.getSpaltenZahl() == SpaltenZahl) )
{
Matrix ergebnis = new Matrix(ZeilenZahl, SpaltenZahl);
for(int y=0; y < ZeilenZahl; y++)
{
for(int x=0; x < SpaltenZahl; x++)
{
ergebnis.setElement(y,x, eineMatrix.getElement(y,x) + getElement(y,x));
}
}
return ergebnis; // Ergebnismatrix zurueckgeben
}
else
return null; // Voraussetzung nicht erfuellt
}
//
// Hauptprogramm einer Java-Anwendung
//
public static void main(String args[])
{
Matrix a = new Matrix(2,2);
a.setElement(0,0,1);
a.setElement(1,1,2);

Matrix b = new Matrix(2,2);
b.setElement(0,1,3);
b.setElement(1,0,4);

Matrix c = a.addiere(b);

System.out.println("Ergebnis:");
System.out.println(c.getElement(0,0) + " " + c.getElement(0,1));
System.out.println(c.getElement(1,0) + " " + c.getElement(1,1));
}
}


import java.applet.*;
import java.awt.*;


public class MatrixGUI extends Applet
{
public void init()
{
//
// wie bei der Anwendung
//
Matrix a = new Matrix(2,2);
a.setElement(0,0,1);
a.setElement(1,1,2);

Matrix b = new Matrix(2,2);
b.setElement(0,1,3);
b.setElement(1,0,4);

Matrix c = a.addiere(b);
//
// Grid-Layout setzen
//
setLayout(new GridLayout(c.getZeilenZahl(),c.getZeilenZahl()));
//
// Fuer jedes Matrixelement einen Druckknopf erzeugen
//
for(int y=0; y < c.ZeilenZahl; y++)
{
for(int x=0; x < c.SpaltenZahl; x++)
{
Float il = new Float(c.getElement(y,x));
add(new Button(il.toString()));
}
}
}
}