0

我正在为 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,并且程序在该语句处跳出构造函数。三元运算符不会根据条件是真还是假来评估它的值。这里发生了什么?

4

2 回答 2

1

您遇到空指针异常。三元运算符的第一个操作数不能是null

当您运行此行时,hasColor必须以 null 的形式输入,从而导致您的程序给您一个运行时错误。这将导致您的程序结束并且vertexSize永远不会被分配。

this.vertexSize = (2 + (hasColor?4:0) + (hasTexCoords?2:0)) * 4;

检查你的 logcat,它应该告诉你是这种情况。

编辑

正如@jahroy 提到的,虽然它会在这一行抛出一个 NPE,但当它传递给构造函数时它可能实际上抛出了 NPE。如果您尝试转换null为布尔值,您还将获得 NPE。

于 2012-07-31T19:07:28.623 回答
0

部分问题是您试图在一行代码中做太多事情。我强烈建议你打破

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

请注意这是多么容易阅读。此外,当您收到错误消息时,更容易找到原因。

于 2012-07-31T19:12:27.067 回答