我正在尝试将一个类的数组的值赋予另一个具有相同类的数组,这里有什么我遗漏的吗?

这个类叫做 Exposicion,有一个 String 和一个 INT 值,所以我用它作为一个数组来从用户那里获取一些输入。


class Exposicion {

public String nombreExpo;

public int duracionExpo;


Exposicion(String nombreExpo, int duracionExpo) {

    this.nombreExpo = nombreExpo;

    this.duracionExpo = duracionExpo;

}

}

使用函数 SortExpo 我计划只复制数组的值,只要 INT 值加起来不等于 180,但是 java 在执行时会标记一个错误:


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

这是整个功能


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;

        }

    }

}


HUX布斯
浏览 132回答 1
1回答

RISEBY

您收到 NullPointerException 异常,因为“expo1”和“sala1”变量均为空。您必须在两个变量上传递对对象的引用。像这样的东西:class SalaExpo(){&nbsp; &nbsp;Exposicion[] expo1=new Exposicion[100];}public class ConsoleMenu {&nbsp; &nbsp;private SalaExpo sala1;&nbsp; &nbsp;void execute(){&nbsp; &nbsp; &nbsp; sala1 = new SalaExpo();&nbsp; &nbsp;}}你也应该像这样 poblate sala1.expo1 数组(不知道这是否是你想要的,但你应该这样做以免得到 NullPointerException):void GuardarExpo(Exposicion[] arrExpoG,int posicion,Exposicion[] arrSala) {&nbsp; &nbsp; &nbsp;/*&nbsp; &nbsp; &nbsp; &nbsp; Bunch&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;of&nbsp; &nbsp; &nbsp; &nbsp; code&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; &nbsp;arrExpoG[posicion] = new Exposicion(inputNombre,inputDuracion);&nbsp; &nbsp; &nbsp;arrSala[posicion]=arrExpoG[posicion];}最后,您应该使用变量“posicion”而不是“sala1.expo1.length”作为参数传递给“imprimirExpo”方法,因为数组“sala1.expo1”的长度为100,这意味着很多空值元素,因为你不是全部:ImprimirExpo(sala1.expo1,posicion);代替:ImprimirExpo(sala1.expo1,sala1.expo1.length);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java