输入和打印矩阵

时间:2015-04-04 02:23:07

标签: java matrix

我一直在努力用Java编写一个输入和打印矩阵的简单程序。它适用于一个矩阵但是只要我放置两个具有不同顺序的矩阵,它就会在方法print()中给出一个超出界限的异常。

package matrices;

import java.util.Scanner;

public class Matrices_Op {
static int i;
static int j;
static int[][] m_Matrice_Nos;

private int p;
private int q;


public static void main(String args[]){

    System.out.print("Enter the first matrice now : \n \n");

    Matrices_Op m1=new Matrices_Op();
    m1.p=2;
    m1.q=2;
    m1.input(m1.p,m1.q);


    System.out.print("Enter the second matrice now : \n \n");

    Matrices_Op m2=new Matrices_Op();
    m2.p=2;
    m2.q=2;
    m2.input(m2.p,m2.q);


    m1.print(m1.p,m1.q);
    m2.print(m2.p,m2.q);

}

public Matrices_Op(){

}

public void matrices_SetOrder(int m_p, int m_q){

}

public static void input(int p,int q){

    m_Matrice_Nos=new int[p][q];

    for(i=0;i<=p-1;i++){
        for(j=0;j<=q-1;j++){
            System.out.print("Enter the number now :\n"+"a"+(i+1)+""+(j+1)+"\n");
            Scanner in = new Scanner(System.in);
            m_Matrice_Nos[i][j] = in.nextInt();
        }
    }
}

public static void print(int p1, int q1){

    for(int ii=0;ii<=p1-1;ii++){
        for(int jj=0;jj<=q1-1;jj++){
            System.out.print(m_Matrice_Nos[ii][jj]+"   ");

        }
        System.out.print("\n");
    }

}

public void multiplication(){

}

public void addition(){

}

}

1 个答案:

答案 0 :(得分:0)

我改进了一些你的代码,记住当你使用静态时它意味着它影响你的类中的每个对象,如果你有静态属性所有对象共享相同的属性

package tabla;
import java.util.Scanner;

public class Matrices_Op {
    int[][] m_Matrice_Nos;

    public Matrices_Op(int p,int q){
        m_Matrice_Nos=new int[p][q];
    }
    public static void main(String args[]){

        System.out.print("Enter the first matrice now : \n \n");

        Matrices_Op m1=new Matrices_Op(2,2);
        m1.input();


        System.out.print("Enter the second matrice now : \n \n");

        Matrices_Op m2=new Matrices_Op(2,2);
        m2.input();


        m1.print();
        System.out.println();
        m2.print();

    }
    public void input(){
        Scanner in = new Scanner(System.in);
        for(int i=0;i<m_Matrice_Nos.length;i++){
            for(int j=0;j<m_Matrice_Nos[i].length;j++){
                System.out.print("Enter the number now :\n"+"a"+(i+1)+""+(j+1)+"\n");
                m_Matrice_Nos[i][j] = in.nextInt();
            }
        }
    }

    public void print(){

        for(int i=0;i<m_Matrice_Nos.length;i++){
            for(int j=0;j<m_Matrice_Nos[i].length;j++){
                System.out.print(m_Matrice_Nos[i][j]+" ");
            }
            System.out.println();
        }

    }

    public void multiplication(){

    }

    public void addition(){

    }


}