Hi, i'm writing a console program which performs the following:
ask the user size of a matrix (user e.g enters 2, the program considers it as 2x2 matrix)
give the user options for the following:
1. add
2. subtract
3. multiply
My code is below but gives be an error when i execute. something like exception in java.lang
well my code is saved in question_5.java
CODE
import java.util.Scanner;
class question_5
{
Scanner input = new Scanner(System.in);
int myMatrix [][];
public void main( String args[])
{
int sizeMatrix;
System.out.printf("Enter size of the matrix must be nxn : ");
sizeMatrix = input.nextInt();
myMatrix = new int[sizeMatrix][sizeMatrix];
menu();
for (int row = 0; row < sizeMatrix; row++)
{
for ( int column = 0; column < row; column++)
{
System.out.printf("\nEnter row %d by column %d :", row, column );
myMatrix[row][column] = input.nextInt();
}
}
}
public void menu()
{
int choice;
System.out.printf("1. Add Matrix\n2.Subtract Matrix\n3.Multiply Matrix\n\nEnter choice : ");
choice = input.nextInt();
while (choice <= 0 || choice > 4)
{
System.out.printf("\nInvalid choice!Please re-enter choice : ");
choice = input.nextInt();
}
switch (choice)
{
case 1:
addMatrix(myMatrix);
break;
case 2:
subMatrix(myMatrix);
break;
case 3:
multMatrix(myMatrix);
break;
}
}
public void outputArray(int myArr[][])
{
for ( int i = 0; i < myArr.length; i++)
{
for ( int j = 0; j < myArr[i].length; j++)
{
System.out.printf("%d" + " ", myMatrix[i][j]);
if ( j == myArr[i].length)
System.out.printf("\n");
}
}
}
//method for adding the 2 matrices
public void addMatrix(int addMMatrix[][] )
{
for ( int iM = 0; iM < addMMatrix.length; iM++)
{
for ( int jm = 0; jm < addMMatrix[iM].length; jm++)
{
addMMatrix[iM][jm] += addMMatrix[iM][jm];
}
}
outputArray(addMMatrix); //display matrix after addition
}
//method for subtracting the 2 matrices
public void subMatrix(int subbMatrix[][] )
{
for ( int M = 0; M < subbMatrix.length; M++)
{
for ( int jmm = 0; jmm < subbMatrix[M].length; jmm++)
{
subbMatrix[M][jmm] -= subbMatrix[M][jmm];
}
}
outputArray(subbMatrix); //display matrix after addition
}
//method for multiplying the matrices
public void multMatrix(int multtMatrix[][] )
{
int l, n, o; //loop control
for( l = 0; l < multtMatrix.length; l++)
for( n = 0; n < multtMatrix.length; n++)
for( o = 0; o < multtMatrix.length; o++)
multtMatrix[l][n] += multtMatrix[l][o]*multtMatrix[o][n];
}
}