Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

User Input Directly to an Array - Question/Help

807601Jun 29 2008 — edited Jun 29 2008
So this is what i need to do. I need the user to input the number of Rows/Columns of 2 matrices, then multiply them together. If this wasnt user input, the program works, but I have to use JOptionPane.showInputDialog to get the input.

Essentially, How do I get a user input to decide the matrix size then fill it accordingly- also which has to be user input.
public class Matrix {


  public static int[][] multiply(int[][] m1, int[][] m2) {
    int m1row = m1.length;
    int m1col = m1[0].length;
    int m2row = m2.length;
    int m2col = m2[0].length;
    if (m1col != m2row)
      throw new IllegalArgumentException("Matrices don't match: " + m1col + " is not equal to " + m2row);
    int[][] result = new int[m1row][m2col];

    // multiply
    for (int i=0; i<m1row; i++)
      for (int j=0; j<m2col; j++)
        for (int k=0; k<m1col; k++)
        result[i][j] += m1[i][k] * m2[k][j];

    return result;
  }


  public static void mprint(int[][] a) {
    int rows = a.length;
    int cols = a[0].length;
    System.out.println("array["+rows+"]["+cols+"] = {");
    for (int i=0; i<rows; i++) {
      System.out.print("{");
      for (int j=0; j<cols; j++)
        System.out.print(" " + a[i][j] + ",");
      System.out.println("},");
    }
    System.out.println(":;");
  }
  public static void main(String[] argv) {




    int x[][] = {
      { 3, 2, 3 },
      { 5, 9, 8 },
    };
    int y[][] = {
      { 4, 7 },
      { 9, 3 },
      { 8, 1 },
    };
    int z[][] = Matrix.multiply(x, y);
    Matrix.mprint(x);
    Matrix.mprint(y);
    Matrix.mprint(z);

  }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 27 2008
Added on Jun 29 2008
1 comment
133 views