1

2 つの行列を加算する小さなプログラムを作成しました。各行列の行数と列数は同じでなければなりません。たとえば、ユーザーが 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");

        }   


    }

           }
4

4 に答える 4

0

もちろん:

while(!isValid(allInputs)) {
    // Ask to enter inputs
}
// do something with valid inputs

...
private boolean isValid(MyTypes inputs) {
    // are my inputs valid?
}
于 2013-08-21T11:52:34.910 に答える