我写了一个小程序,将两个矩阵加在一起。每个矩阵必须具有相同的行数和列数。如果用户输入例如 2x2 + 3x3,是否有一种巧妙的方法可以让用户再次回到程序的开头?
import java.util.*;
import javax.swing.*;
public class MatrixAdd {
public static void main (String[] args)
{
System.out.println("Please enter the number of rows you want in Matrix 1 => ");
Scanner stdio = new Scanner (System.in);
int rowA = stdio.nextInt();
System.out.println("Please enter the number of columns you want in Matrix 1 => ");
int columnA = stdio.nextInt();
System.out.println("Please enter the number of rows you want in Matrix 2 => ");
int rowB = stdio.nextInt();
System.out.println("Please enter the number of columns you want in Matrix 2 => ");
int columnB = stdio.nextInt();
if (rowA != rowB || columnA != columnB)
{
System.out.println("Matrix 1 and Matrix 2 must have same number of rows and columns");
}
int arrayA[][] = new int[rowA][columnA];
for(int i = 0; i < rowA; i++)
{
for(int j = 0; j < columnA; j++)
{
System.out.println("Please enter element for row " + (i+1) + " column "+ (j+1) + " of Matrix 1 => ");
arrayA[i][j] = stdio.nextInt();
}
}
int arrayB[][] = new int[rowB][columnB];
for(int i = 0; i < rowB; i++)
{
for(int j = 0; j < columnB; j++)
{
System.out.println("Please enter element for row " + (i+1) + " column "+ (j+1) + " of Matrix 2 => ");
arrayB[i][j] = stdio.nextInt();
}
}
int arrayC[][] = new int[rowA][columnA];
for(int i = 0; i < rowB; i++)
{
for(int j = 0; j < columnB; j++)
{
arrayC[i][j] = arrayA[i][j] + arrayB[i][j];
}
}
for(int i = 0; i < rowA; i++)
{
System.out.print("[");
for(int j = 0; j < columnA; j++)
{
System.out.print(" " + arrayC[i][j]);
}
System.out.print(" ] " + "\n");
}
}
}