我正在 Eclipse 中为 Android 项目编写一个顶点类,并且在构造函数中我遇到了运行时错误。这是构造函数...
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,并且程序会在该语句处脱离构造函数。三元运算符不会根据条件是真还是假来计算其值。这是怎么回事?
最佳答案
您遇到空指针异常。三元运算符的第一个操作数不能为 null
。
当您运行此行时,hasColor
必须为 null,导致您的程序出现运行时错误。这将导致您的程序结束,并且 vertexSize
将永远不会被分配。
this.vertexSize = (2 + (hasColor?4:0) + (hasTexCoords?2:0)) * 4;
检查您的 logcat,它应该显示情况确实如此。
编辑
正如 @jahroy 提到的,虽然它会在这一行抛出一个 NPE,但它实际上可能在传递给构造函数时抛出 NPE。如果您尝试将 null
转换为 boolean 值,您也会得到一个 NPE。
关于java - 三元语句突破构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11747047/