我在按特定顺序打印矢量时遇到一些麻烦。如果有人可以帮助我。感谢。
public static Vector sequence(int length, int start, int step) {
/* to do
length 1, start 1, step 1 => [1]
length 2, start 2, step 2 => [2 4]
length 3, start 3, step 3 => [3 6 9]
length 4, start 4, step 4 => [4 8 12 16]
length 5, start 5, step -1 => [5 4 3 2 1]
*/
System.out.println(length + ", "+ start+ ", " +step);
Vector vector = new Vector(length);
for (int i = 0; i < length; i++) {
int total = start+step;
vector.elements[i] = start+step;
//System.out.print(vector.elements[i]);
}
//return new Vector(length);
return vector;
}
答案 0 :(得分:0)
您需要将step
与i
相乘,并使用Vector
的正确方法添加新元素,即Vector.add()。另外,您最好将类型参数添加到Vector
:
Vector<Integer> vector = new Vector<>(length);
for (int i = 0; i < length; i++) {
int total = start+step*i;
vector.add(total); // add total as last element of the vector
}