【问题标题】:How to add a variable to an array如何将变量添加到数组
【发布时间】:2011-11-22 23:26:56
【问题描述】:

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

//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 更改为该浮点值

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

【问题讨论】:

  • 你能发布更多的例外情况吗?能否也说明一下地图是如何定义的?
  • 什么是mapy 是干什么用的?
  • “地图”的类型是什么?错误的全部信息是什么?可能不是下一行? (generator.nextGaussian();)
  • 过于本地化。我怎么知道它太本地化了? 没有办法为这个问题写一个好的标题。 1) 读取异常,发布异常,以某种有意义的方式使用异常来解决问题 2) 发布所有适用的代码。此外,作为一个 nit,不可能将变量添加到数组 - 只能添加 values
  • 好吧,-1 是因为没有真正倾听 cmets 和更新问题。

标签: java arrays variables loops random


【解决方案1】:

我猜你遇到了两个例外之一:

  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..
}

【讨论】:

  • @JAW1025:那么...你要告诉我们你得到的异常类型是什么吗?我的回答只是我最好的猜测。您发布的信息太少,我无法确定。
  • 刚刚试了一下,完美的答案,解决了一切,谢谢! (很抱歉第一次不清楚。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-23
  • 1970-01-01
  • 2012-09-21
相关资源
最近更新 更多