Perkalian Matriks dengan Java

import javax.swing.*;

public class MatriksKali
{
	public static void main (String[] args) throws IOException
	{
		String warning = "Ingat!!!!\nIni Pekalian matriks\nKOLOM matriks A harus sama dengan BARIS Matriks B ";
		JOptionPane.showMessageDialog (null, warning);

		//Mendapatkan orde Matriks A
		String ba = "";
		ba = JOptionPane.showInputDialog ("Masukkan jumlah baris Matriks A: ");
			int barisA = Integer.parseInt (ba);
		String ka = "";
		ka = JOptionPane.showInputDialog ("Masukkan jumlah kolom Matriks A: ");
		int kolomA = Integer.parseInt (ka);
		int[][] matriksA = new int [barisA][kolomA];

		//Mendapatkan orde Matriks B
		String bb = "";
		bb = JOptionPane.showInputDialog ("Masukkan jumlah baris Matriks B: ");
		int barisB = Integer.parseInt (bb);
		String kb = "";
		kb = JOptionPane.showInputDialog ("Masukkan jumlah kolom Matriks B: ");
		int kolomB = Integer.parseInt (kb);
		int[][] matriksB = new int [barisB][kolomB];

		//Mendeklarasikan orde matriks C
		int[][] matriksC = new int [barisA][kolomB];

		//Memasukkan nilai Matriks A
		for (int i=0;i<barisA;i++)
		{
			for (int j=0;j<kolomA;j++)
			{
				String input = "";
				input = JOptionPane.showInputDialog ("Masukkan nilai Matriks A indeks ("+i+","+j+")");
				int k = Integer.parseInt (input);
				matriksA [i][j] = k;
			}
		}

		//Memasukkan nilai Matriks B
		for (int i=0;i<barisB;i++)
		{
			for (int j=0;j<kolomB;j++)
			{
				String input = "";
				input = JOptionPane.showInputDialog ("Masukkan nilai Matriks B indeks ("+i+","+j+")");
				int k = Integer.parseInt (input);
				matriksB [i][j] = k;
			}
		}

		//Merumuskan perkalian Matriks A dengan MatriksB (MatriksA x MatriksB)
		for (int i=0;i<barisA;i++)
		{
			for (int j=0;j<kolomB;j++)
			{
				matriksC [i][j] = 0;
				for (int k=0;k<kolomA;k++)
				{
					int l = matriksA [i][k] * matriksB [k][j];
					matriksC [i][j] = matriksC [i][j] + l;
				}
			}
		}

		//Mencetak Matriks A
		System.out.print ("\nMatriks A: \n");
		for (int i=0;i<barisA;i++)
		{
			for (int j=0;j<kolomA;j++)
			{
				System.out.print (matriksA [i][j]+" ");
			}
			System.out.println ();
		}

		//Mencetak Matriks B
		System.out.print ("\nMatriks B: \n");
		for (int i=0;i<barisB;i++)
		{
			for (int j=0;j<kolomB;j++)
			{
				System.out.print (matriksB [i][j]+" ");
			}
			System.out.println ();
		}

		//Mencetak hasil Penjumlahan Matriks
		System.out.print ("\nHasil perkalian Matriks A dengan Matriks B (Matriks A x matriks B) adalah: \n");
		for (int i=0;i<barisA;i++)
		{
			for (int j=0;j<kolomB;j++)
			{
				System.out.print (matriksC [i][j]+" ");
			}
			System.out.println ();
		}
	}
}
Advertisement