如何向数组添加变量

发布于 2024-12-17 10:29:47 字数 817 浏览 0 评论 0原文

我正在尝试将数组中的值设置为变量。这是我的代码:

//init the array as a float
//I have tried to put a value in the brackets, but it returns a different error.
//I initialized it this way so I could call it from other methods
private float[] map;

// generate a "seed" for the array between 0 and 255
float x = generator.nextInt(256);
int n = 1;
// insert into the first 25 slots
while(n <= 25) {
    // here's my problem with this next line
    map[n] = x;
    double y = generator.nextGaussian();
    x = (float)Math.ceil(y);
    n = n + 1;
}

我用错误标记了该行,返回的错误是:“未捕获的异常抛出......”。我做错了什么???提前致谢。

编辑-----

这是整个例外:

    Uncaught exception thrown in Thread[LWJGL Renderer Thread,5,main]

我使用 y 生成随机高斯,然后将其转换为浮点值并将 x 更改为该浮点值

我很确定这是那条线,因为这就是我的编译器告诉我的。

I am trying to set the value in an array to a variable. Here is my code:

//init the array as a float
//I have tried to put a value in the brackets, but it returns a different error.
//I initialized it this way so I could call it from other methods
private float[] map;

// generate a "seed" for the array between 0 and 255
float x = generator.nextInt(256);
int n = 1;
// insert into the first 25 slots
while(n <= 25) {
    // here's my problem with this next line
    map[n] = x;
    double y = generator.nextGaussian();
    x = (float)Math.ceil(y);
    n = n + 1;
}

I marked the line with my error, the error returned is: "uncaught exception thrown in...". What am I doing wrong??? Thanks in advance.

EDIT-----

Here's the whole exception:

    Uncaught exception thrown in Thread[LWJGL Renderer Thread,5,main]

I'm using y to generate a random gaussian, then converting it into a float value and changing x into that float value

I'm pretty sure that It's that line, because that's what my compiler told me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

差↓一点笑了 2024-12-24 10:29:47

我猜您会遇到以下两个异常之一:

  1. 您收到 NullPointerException 因为已将映射初始化为 null。使用例如分配非空值:

    private float[] map = new float[25];
    
  2. 您将收到 IndexOutOfBoundsException,因为您使用的是基于 1 的索引而不是基于 0 的索引。

更改此:

int n = 1;
while(n <= 25) {
    // etc..
    n = n + 1;
}

对于此 for 循环:

for (int n = 0; n < 25; ++n) {
    // etc..
}

I'm guessing that you get one of two exceptions:

  1. You are getting a NullPointerException because have initialized map to null. Assign a non-null value using for example:

    private float[] map = new float[25];
    
  2. You are getting an IndexOutOfBoundsException because you are using 1-based indexing instead of 0-based indexing.

Change this:

int n = 1;
while(n <= 25) {
    // etc..
    n = n + 1;
}

To this for loop:

for (int n = 0; n < 25; ++n) {
    // etc..
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文