import java.io.*;
public class KeyInput
{
public static int readInt() throws IOException
{
String s;
InputStreamReader ir;
BufferedReader in;
ir=new InputStreamReader(System.in);
in=new BufferedReader(ir);
System.out.print(": ");
s=in.readLine();
int i=Integer.parseInt(s);
return i;
}
public static double readDouble() throws IOException
{
String s;
InputStreamReader ir;
BufferedReader in;
ir=new InputStreamReader(System.in);
in=new BufferedReader(ir);
s=in.readLine();
double d=Double.parseDouble(s);
return d;
}
}
import java.io.IOException;
public class Matrix{
private int rows;
private int cols;
double[][] data;
public Matrix(){
this(0,0);
}
public Matrix(int rows,int cols){
this.rows = rows;
this.cols = cols;
data = new double[rows][cols];
}
public Matrix(int rows,int cols,double data[][]){
this.rows = rows;
this.cols = cols;
this.data = data;
}
public void setData(int rows,int cols,double value){
this.rows = rows;
this.cols = cols;
data[rows][cols] = Math.random()*value;
}
public double getData(int rows,int cols){
return data[rows][cols];
}
public Matrix multiply(Matrix B){
Matrix A = this;
if(A.cols!=B.rows)
new IllegalArgumentException("矩阵不匹配!");
Matrix C = new Matrix(A.rows,B.cols);
for(int i=0; i<C.rows; i++)
for(int j=0; j<C.cols; j++)
for(int k=0; k<A.cols; k++)
C.data[i][j] += (A.data[i][k]*B.data[k][j]);
return C;
}
public String toString(){
StringBuffer s = new StringBuffer();
int rows = data.length;
int cols = data[0].length;
s.append("Matrix ["+rows+"]["+cols+"] ="+"\n");
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++)
s.append(" "+data[i][j]+" ");
s.append("\n");
}
s.append("\n");
return s.toString();
}
public static void main(String args[]) throws IOException{
int rows,cols;
rows = KeyInput.readInt();
cols = KeyInput.readInt();
Matrix A = new Matrix(rows,cols);
for(int i=0;i<A.rows;i++){
for(int j=0;j<A.cols;j++)
A.setData(i, j, 10.0);
}
rows = KeyInput.readInt();
cols = KeyInput.readInt();
Matrix B = new Matrix(rows,cols);
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++)
B.setData(i, j, 10.0);
}
System.out.println(A.multiply(B).toString());
}
}
Exception in thread "main" [color=red]java.lang.ArrayIndexOutOfBoundsException[/color]: 0
at test.Matrix.toString(Matrix.java:48)
at test.Matrix.main(Matrix.java:76)
为什么?