在Vector类中显示数组内的元素

时间:2014-01-09 14:51:19

标签: java arrays class oop object

这是我的Vector Class

public class SimpleVector {

private double []vector;


public SimpleVector(int length) {
    this.vector = new double[length];
}

public SimpleVector(int length, double vals) {
    this(length);
    Arrays.fill(vector,vals);

}

public SimpleVector(double[] vector) {
    this.vector = new double[vector.length];
    System.arraycopy(vector,0,this.vector,0,vector.length);//arraycopy(Object src,
    // int srcPos, Object dest, int destPos, int length)

}

public final int getLength() {
    return this.vector.length;
}

public void print() {
    System.out.print("Type = Vector  ,  ");
    System.out.print("numRows = "+vector.length);
    for (int i = 0; i < vector.length; i++) {
        System.out.println(vector[i]);
    }

当我使用vector类创建一个对象并调用我的print方法时,它不会显示向量中的所有元素,并且行数是错误的。但是当我调用我的getLength方法时,它正确地显示了向量

中的行数

public static void main(String [] args){

    double[] array = new double[] {1,2};
    SimpleVector o = new SimpleVector(array);
    o.print();

}

输出: Type = Vector,numRows = 21

2.0

1 个答案:

答案 0 :(得分:0)

由于缺少换行符,您会感到困惑。试试这个:

public void print() {
    System.out.print("Type = Vector  ,  ");
    System.out.println("numRows = "+vector.length); //use println instead 
    for (int i = 0; i < vector.length; i++) {
        System.out.println(vector[i]);
    }
}

输出应为:

Type = Vector  ,  numRows = 2
1.0
2.0