#java #oop #matrix
#java #ооп #матрица
Вопрос:
Я начинаю Java ООП и выполняю упражнение по созданию класса, Matrix
который может выполнять такие операции, как sum()
.
Я написал приведенный ниже код, но в методе add()
есть проблема. Когда я компилирую код, на экране появляется эта ошибка:
Matrix.java:98: error: array required, but Matrix found
result[i][j] = this[i][j] b[i][j];
^
Matrix.java:98: error: array required, but Matrix found
result[i][j] = this[i][j] b[i][j];
^
Matrix.java:98: error: array required, but Matrix found
result[i][j] = this[i][j] b[i][j];
Как я могу исправить ошибку? Вот код:
import java.util.Scanner;
public class Matrix{
int[][] mat;
int m = 0;
int n = 0;
public Matrix(int l,int m, int n){
this.m = m;
this.n = n;
mat = new int[m][n];
for(int i = 0; i < m; i){
for(int j = 0; j < n; j){
mat[i][j] = l;
}
}
}
public Matrix(int m, int n){
this.m = m;
this.n = n;
mat = new int[m][n];
Scanner tastiera = new Scanner(System.in);
int i = 0;
int j = 0;
for(i = 0; i < m; i){
for(j = 0; j < n; j){
int c = i 1;
int b = j 1;
System.out.print("inserire m[" c "][" b "]: ");
mat[i][j] = tastiera.nextInt();
System.out.println();
}
}
}
public void set(int i, int j){
assert (i - 1 <= m):
"Errore, l'indice i deve essere al piu': " m;
assert (j - 1<= n):
"Errore, l'indice j deve essere al piu': " n;
int c = i 1;
int b = j 1;
Scanner tastiera = new Scanner(System.in);
System.out.print("inserire il numero m[" c "][" b "]: ");
mat[i - 1][j - 1] = tastiera.nextInt();
}
public int get(int i, int j){
return mat[i - 1][j - 1];
}
public void stampa(){
int i = 0;
int j = 0;
for(i = 0; i < mat.length; i){
for(j = 0; j < mat[i].length; j){
System.out.print(mat[i][j] " ");
}
System.out.println();
}
}
public int rows(){
return this.m;
}
public int columns(){
return this.n;
}
public Matrix add(Matrix b){
Matrix result = new Matrix(0,this.m, this.n);
assert(this.m != b.m):
"Errore dimensioni delle righe";
assert(this.n != b.n):
"Errore dimensioni delle colonne";
for (int i = 0; i < this.m; i){
for(int j = 0; j < this.n; j){
result[i][j] = this[i][j] b[i][j];
}
}
return resu<
}
}
// P.S. спасибо!!!!
Ответ №1:
Аргумент, переданный вашему методу add, имеет тип Matrix. Что вам нужно, так это двумерный массив. Вы должны изменить это на что-то вроде приведенного ниже.
result.mat[i][j] = this.mat[i][j] b.mat[i][j];