当我创建一个二维数组并初始化数组的一个维度时,一切正常,但如果我从另一个类中调用它,则无效。为什么呢?
import java.util.Scanner;
public class Coursework {
public static void main(String[] args) {
int verticalMatrix; // vertical size of Matrix
int horisontMatrix; // horisont
System.out.println("Enter vertical size of Matrix ");
Scanner sc = new Scanner(System.in);
verticalMatrix = sc.nextInt();
int [][] matrix = new int [verticalMatrix][];
}}
此代码有效,但是当我使用扩展类Matrix时,我只能保存一个大小(verticalMatrix)。如何解决?
public class Coursework extends Matrix {
public static void main(String[] args) {
int verticalMatrix; // vertical size of Matrix
int horisontMatrix; // horisont
System.out.println("Enter vertical size of Matrix ");
Scanner sc = new Scanner(System.in);
verticalMatrix = sc.nextInt();
int [][] matrix = new int [verticalMatrix][];
Matrix Class
public class Matrix {
public static int [][] Matrix;
public void getSize(){
System.out.println("This method still epmty");
}
}
答案 0 :(得分:0)
您的int数组变量就像您的类(Matrix
)一样被调用。这可能不会导致错误,但不是首选。您可以传递构造函数的数组的垂直长度,如下所示:
public class Matrix {
public static int [][] matrix;
public void Matrix(int verticalLength){
this.matrix = new int[verticalLength][];
}
public void getSize(){
System.out.println("This method still epmty");
}
}