I should carry out this exercise in the creation of a class, I uploaded this is the professor's solution, in sum and product methods can not quite figure out what place and why use "A".
class Vettore {
private int[] V = new int[6];
public Vettore(int[] X) {
if (X.length != 6)
throw new BadDataException();
for (int i = 0; i < 6; i++)
if (X[i] < 0)
throw new BadDataException();
else
V[i] = X[i];
}
public Vettore() {}
public Vettore somma(Vettore X) {
int[] A = new int[6];
for (int i = 0; i < 6; i++)
A[i] = V[i] + X.V[i];
return new Vettore(A);
}
public Vettore prodotto(Vettore X) {
int k = 0;
for (int i = 0; i < 6; i++)
k += V[i] * X.V[i];
return k;
}
public int get(int i) {
if (i < 0 || i > 5)
throw new BadDataException();
return V[i];
}
public String toString() {
String t = "( ";
for (int i = 0; i < 6; i++)
t += V[i] + (i == 5 ? " " : ", ");
return t + ")";
}
public boolean equals(Vettore X) {
for (int i = 0; i < 6; i++)
if (V[i] != X.V[i])
return false;
return true;
}
}
As far as I see it, and assuming somma
means sum
and prodotto
means product
, The A
is needed because you have to store the sum values of the V
and XV
arrays for every index . If you didn't use another array
for this, you wouldn't be able to achive adding the appropriate indexes in somma
for example. This method stands for - as I see it - Adding the two arrays' appropriate elements
.
EDIT: another thing. Are you sure that the return types match variables to return? I elaborated the use of somma
but didn't pay attention that prodotto
has a wrong return type, just as it was said in the comments.
You might want to correct the prodotto
method definition as -
public Vettore prodotto(Vettore X) { int[] K = new int[6]; // deault values are 0 for (int i = 0; i < 6; i++) K[i] += V[i] * XV[i]; return new Vettore(K); }
This would evaluate the product of the array field V
for two instances of class Vettore
namingly X
the input param and the current instance that you would call the method from.
return new Vettore(K);
creates a new instance of Vettore
class with K as arrays field, while executing the constructor logic in place as follows -
public SumAndProductExercise(int[] X) { if (X.length != 6) { // length of the array is 6 or not throw new BadDataException(); } for (int i = 0; i < 6; i++) { if (X[i] < 0) { // all the elements of array are >=0 or not throw new BadDataException(); } else { V[i] = X[i]; // the field on the new instance } } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.