[英]Ternary statement breaking out of contructor
我在Eclipse和构造函数内为android项目编写一个vertices类,遇到运行时错误。 这是构造函数...
public Vertices(GLGraphics glGraphics, int maxVertices, int maxIndices, boolean hasColor, boolean hasTexCoords)
{
this.glGraphics = glGraphics;
this.hasColor = hasColor;
this.hasTexCoords = hasTexCoords;
this.vertexSize = (2 + (hasColor?4:0) + (hasTexCoords?2:0)) * 4;
ByteBuffer buffer = ByteBuffer.allocateDirect(maxVertices * vertexSize);
buffer.order(ByteOrder.nativeOrder());
vertices = buffer.asFloatBuffer();
if(maxIndices > 0)
{
buffer = ByteBuffer.allocateDirect(maxIndices * Short.SIZE / 8);
buffer.order(ByteOrder.nativeOrder());
indices = buffer.asShortBuffer();
}
else
{
indices = null;
}
}
在此语句中:
this.vertexSize = (2 + (hasColor?4:0) + (hasTexCoords?2:0)) * 4;
我正在计算顶点的大小(以字节为单位)。 问题在于,每当执行三元运算时,vertexSize都将保持为0,并且程序会在该语句中脱离构造函数。 三元运算符不会根据条件是true还是false来评估其值。 这里发生了什么?
您正在遇到空指针异常。 三元运算符的第一个操作数不能为null
。
运行此行时, hasColor
必须为null,这会导致程序给您运行时错误。 这将导致您的程序结束并且永远不会分配vertexSize
。
this.vertexSize = (2 + (hasColor?4:0) + (hasTexCoords?2:0)) * 4;
检查您的logcat,它应该显示这种情况。
编辑
正如@jahroy所提到的,尽管它将在此行上抛出NPE,但当它传递到构造函数中时,实际上可能会抛出NPE。 如果尝试将null
转换为布尔值,则还将获得NPE。
问题的一部分是您试图在一行代码中做太多事情。 我强烈建议你休息
this.vertexSize = (2 + (hasColor?4:0) + (hasTexCoords?2:0)) * 4;
分成大约三行代码:
int colorWeight = hasColor ? 4 : 0;
int texCoordWeight = hasTexCoords ? 2 : 0;
this vertexSize = (2 + colorWeight + texCoordWeight) * 4
请注意,这很容易阅读。 同样,当您收到错误消息时,更容易找出原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.