【问题标题】:Displaying elements inside the array in the Vector Class在 Vector 类中显示数组内的元素
【发布时间】:2014-01-28 04:43:06
【问题描述】:

这是我的向量类

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]);
    }

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

public static void main(String[] args) {

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

}

输出: 类型 = 矢量 , numRows = 21

2.0

【问题讨论】:

  • 它产生Type = Vector , numRows = 21.0 &lt;new line&gt; 2.0 这是正常行为,因为您没有在此处添加新行分隔符System.out.print("numRows = "+vector.length );

标签: java arrays class oop object


【解决方案1】:

您会因为缺少换行符而感到困惑。试试这个:

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

【讨论】:

    猜你喜欢
    • 2019-08-27
    • 2019-07-21
    • 1970-01-01
    • 2020-06-27
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-07
    相关资源
    最近更新 更多