简体   繁体   中英

I'm trying to give the value of an array of a class to another array with the same class, is there something I'm missing here?

The class is called Exposicion and has a String and an INT value, so I used it as an array to grab some input from the user.

class Exposicion {
public String nombreExpo;
public int duracionExpo;

Exposicion(String nombreExpo, int duracionExpo) {
    this.nombreExpo = nombreExpo;
    this.duracionExpo = duracionExpo;
}
}

With the Function SortExpo I plan to copy only the values of the array as long as the INT values don't add up to 180, but java flags an error when doing:

      arrExpoT[posHor].nombreExpo = arrExpoS[k].nombreExpo;

This is the whole function

void SortExpo(Exposicion[] arrExpoS,int posicion,Exposicion[] arrExpoT){

    int poshor=0;
    int total=0;
    for (int k = 0; k < posicion; k++) {
        if ( total < 180 || arrExpoS[poshor].nombreExpo != "TOMADO123") {
            arrExpoT[poshor].nombreExpo = arrExpoS[k].nombreExpo;
            arrExpoT[poshor].duracionExpo = arrExpoS[k].duracionExpo;
            arrExpoS[poshor].nombreExpo = "TOMADO123";
            total = total + arrExpoS[k].duracionExpo;
            poshor++;
        } else {
            k = posicion;
        }
    }
}

Error

I've added the .java file in this link

Also Main.java if this helps

You are getting a NullPointerException because "expo1" and "sala1" variables are both null. You have to pass a reference to an object on both variables. Something like this:

class SalaExpo(){
   Exposicion[] expo1=new Exposicion[100];
}

public class ConsoleMenu {

   private SalaExpo sala1;

   void execute(){
      sala1 = new SalaExpo();
   }
}

Also you should poblate the sala1.expo1 array, like this (don't know if this is what you are intending but you should do this in order not to get a NullPointerException) :

void GuardarExpo(Exposicion[] arrExpoG,int posicion,Exposicion[] arrSala) {

     /*
        Bunch
         of
        code

     */

     arrExpoG[posicion] = new Exposicion(inputNombre,inputDuracion);
     arrSala[posicion]=arrExpoG[posicion];
}

Finally, you should use the variable "posicion" instead of "sala1.expo1.length" to pass as argument to the "imprimirExpo" method, since the array "sala1.expo1" has a length of 100, that means a lot of null elements since you are not poblating it all:

ImprimirExpo(sala1.expo1,posicion);

instead of:

ImprimirExpo(sala1.expo1,sala1.expo1.length);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM