I have writen a code for adding (math +) two arrays. Actually, I have two arrays of a class I have also designed, that has two attributess, one of wich is an integer.
I would like to sum (add element by element) one array on the other by adding the integer attribute of each element to the integer attribute of the other element.

I have a compiling time error that says "unexpected type" in the line I mark with an "<==="
Here is my code:

package practica_2010;
package practica_2010;

/**
 * Write a description of class PAGS here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
//Name I will give to the statistics array's position, so that I can refer them to as "this.statsArray[TRESES]++" whithout needing to 
//remember exactly wich was the apropriate index to store the number of digit 3 I have encountered so far
public class statIndex // continene los nombres que van a tener las distintas posiciones o elementos del array de estadísticas.
                            // static para que sean públicamente visibles sin necesitar instanciar una clase statIndex
                            // final para que no se creen instancias.
{
    public final static int CARACTERES = 0;     // characthers. they go in the position 0 of the array
    public final static int LETRAS = 1;         // letters
    public final static int VOCALES = 2;        // vowels
    public final static int CONSONANTES = 3;    // consonnants
    public final static int SIMBOLOS = 4;       // symbols
    public final static int DIGITOS = 5;        // digits
    public final static int UNOS = 6;           // 1s
    public final static int DOSES = 7;          // 2s
    public final static int TRESES = 8;         // 3s
    public final static int CUATROS = 9;        // 4s
    public final static int CINCOS = 10;
    public final static int SEIS = 11;
    public final static int SIETES = 12;
    public final static int OCHOS = 13;
    public final static int NUEVES = 14;
    public final static int CEROS = 15;
    public final static int AES = 16;           //As, Bs, Cs... Xs, Ys, Zs...
    public final static int BES = 17;
    public final static int CES = 18;
    public final static int DES = 19;
    public final static int ES = 20;
    public final static int EFES = 21;
    public final static int GES = 22;
    public final static int HACHES = 23;
    public final static int IES = 24;
    public final static int JOTAS = 25;
    public final static int KAS = 26;
    public final static int ELES = 27;
    public final static int EMES = 28;
    public final static int ENES = 29;
    public final static int EÑES = 30;
    public final static int OES = 31;
    public final static int PES = 32;
    public final static int QUES = 33;
    public final static int ERRES = 34;
    public final static int ESES = 35;
    public final static int TES = 36;
    public final static int UES = 37;
    public final static int UVES = 38;
    public final static int DOBLEUVES = 39;
    public final static int EQUIS = 40;
    public final static int YES = 41;
    public final static int ZETAS = 42;
    public final static int FPAL = 43;
    public final static int FFRAS = 44;
    public final static int FPAR = 45;
    public final static int FPAG = 46;
    public final static int FDL = 47;
    public final static int PALABRAS = 48;
    public final static int NUMEROS = 49;
    public final static int FRASES = 50;
    public final static int PARRAFOS = 51;
    public final static int PAGINAS = 52;
//     public final static int BASICOS = 53;
//     public final static int BASICOS = 54;
//     public final static int BASICOS = 55;
//     public final static int BASICOS = 56;
//     public final static int BASICOS = 57;
//     public final static int BASICOS = 58;

}
// somebody has suggested that I use a Map, instead of so many constants... in where I have something like 1 corresponds to LETRAS (spanish for letters)
/** 
 * statItem is a class for storing values of a magnitude statistics: "CHARACTERS: 50" meanning that there are 50 characters. 
 * It has two values, String and integer, so that the first value matches one of the statIndex (see below) values
 * This class is to make objects that forms the Array of statistics of each complex element. Thus, to print statistics of such complex objects, an 
 * iterator would print statItem.magnitud+"  "+statItem.valor. To access a certain magnitude, we use the statIndex constants on the arraylist of statItems
 * Each elementoCompuesto object, has this kind of arraylist, statsArray estadisticas. statsArray is an arraylist<statItems>, so, estadisticas[SIMBOLOS] should yield 
 * a statITem object's reference whose elements can be accessed (estadisticas[SIMBOLOS].getMagnitud is the string "Simbolos")
 */

public class statItem {
    private String magnitud;
    private Integer valor;
    
    // method to set both values
    public void set(String magn, Integer cantidad){
        this.magnitud=magn;
        this.valor=cantidad;
    }
    //method to set magnitud
    public void set(String magn){
        this.magnitud=magn;    }
    //method to set valor
    public void set(Integer cantidad){
        this.valor=cantidad;}
    //method to give magnitud
    public String getMagnitud(){
        return this.magnitud;}
    //method to give valor
    public Integer getValor(){
        return this.valor;}
}
/**
 * Array de 52 elementos de tipo statItem, que guarda las estadísticas de cada elemento complejo.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class statsArray
{
    // instance variables - replace the example below with your own
    private statItem [] statVect;
    

    /**
     * Constructor for objects of class statsArray
     */
    public statsArray()
    {
        statVect = new statItem[52];
    }

    public void addStats (statItem [] otroVect){
        for (int i=0; i<this.statVect.length;i++){
        this.statVect[i].getValor()+=otroVect[i].getValor(); //<===
        }
    }
        
}

You may replace the code in line 24 where the error occurs by the following two lines of code:

int va = this.statVect[i].getValor();
     va += otroVect[i].getValor();
     this.statVect[i].set(va);

Can you answer me Why we should modify in this way?

commented: Allowing the OP to think +6

I guess that this has to do with the way I declare the method set in the statItem object...

I have replaced it with a more clear setValor, and, similarly as you suggested, I changed the code to this:

public void addStats (statItem [] otroVect){
        for (int i=0; i<this.statVect.length;i++){
            Integer a = this.statVect[i].getValor();
            Integer b =      otroVect[i].getValor();
            this.statVect[i].setValor(a+b);
        }
    }

ankilosado, I have a question for you:
Why do you declare the class statItem has an attribute valor of type of Integer instead of the primitive type int? Integer is the wrapper class of int. Am I right?

tong1, thanks for your quick response. I am not sure what to do in that respect. I am very very new to Java but have a project to complete for my university classroom. I have had some problems when working with int type, as I cannot reference them in some situations (I receive some errors) and when trying to fix'em in the Internet, I have read that these problems could be solved wrapping int with Integer, but It ma be wrong so, if you have any suggestion, I'm eager to know about it.

I find it difficult to understand the shadowing, privacy and inheritance...
I declared a class that has an array as an attribute. I have declared it as private.
Then I created a series of classes that inherit from the former. I thought that these new classes already had the attributa as part of themselves, but I find an error at compiling time stating that I have declared the array as private. The sub-classes try to use their (I assumed) own arrray with this.theArray.someMethod(), but this is when I got the error...

Should I declare it as public or should I have to (again and again and again) code a method to pass the attribute between a parent and his children?

I declared it public. IS the only way I have found to fix this.

Declare the attributes/methods as protected rather than public so that only the methods of its subclass may have access to them.

Thankyou, tong1. I did not find this (bad reader I can be), but will give it a try.

I have more issues in my whole code, but they have no relation with this thread. I will start another thread, I think. It is about an error in compiling time that states that a variabe may not have been initialized. I am using a console textual menu. IF the user hits '1', I read a txt file and build a complex structure where objects are composed of others (pages of paragraphs, paragraphs of phrases, phrases of words...) and store this structure in a Document object.
If the user hits '2', I use this Documento to perform some activities, and there is where I get the error. Should I start a new thread?

I find it difficult to understand the shadowing, privacy and inheritance...
I declared a class that has an array as an attribute. I have declared it as private.
Then I created a series of classes that inherit from the former. I thought that these new classes already had the attributa as part of themselves, but I find an error at compiling time stating that I have declared the array as private. The sub-classes try to use their (I assumed) own arrray with this.theArray.someMethod(), but this is when I got the error...

Should I declare it as public or should I have to (again and again and again) code a method to pass the attribute between a parent and his children?

Yes, the child classes do have as attributes any members declared at the parent classes. The issue was that when declared private they cannot be accessed form outside the class even from their child classes.

Apart from declared public or protected, you can have get methods. With that way, they can be altered by methods in the parent class but accessed by any other class.

class A {
  private int someVar = 0;

  // in here there is code that does some stuff with the someVar variable.
  // You do not want other classes to be able to change it.

  // But in order for its value to be accessible:
  public int getSomeVar() {
     return someVar;
  }
}
class B extends A {
   public void print() {
     System.out.println("Some Var: "+getSomeVar());
   }
}

Hmm, JavaAddict,
I'm so new to this language that I can't retain all that I see. I believed that once I declare a sub-class, it just had access to its parent's properties with no restrictions, as if they were its, but now I can see it's not that easy (why the hell not? This looks like a way to restrict inheritance, but there are another ways to put restrictions to inheritance... but I am not here to make you waist time with this ;-)).

I will try what you say and let you know. Currently I am fine with declaring it public though I will try if I had time before the deadline to send my homework, as this improvement surely would be for better grades... it's better code.
I will let you know.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.