【问题标题】:Int array fills with last intInt 数组用最后一个 int 填充
【发布时间】:2017-08-10 13:23:18
【问题描述】:

我正在尝试用整数填充一个 int 数组。但是,当我打印出数组时,我只会得到相同的最后一个值,重复 25 次,这不是我想要的。我想用从蓝牙服务获得的不同整数填充数组...

weightFromDevice = intent.getExtras().getInt(BluetoothService.MESSAGE_WEIGHT_DATA); //take int values from bluetooth service

int [] _weightCount = new int[25]; // Array has a length of 25
Arrays.fill(_weightCount, weightFromDevice); //Trying to fill array with the different ints

String res = Arrays.toString(_weightCount); //Array to string for printing

displayData(res); // calling method to print array

我做错了什么?

【问题讨论】:

  • 你只有一个int 为什么你认为你有25个不同的int?
  • 您是否尝试过调试和检查程序的状态?
  • 打印 weightFromDevice。这个变量的声明到底在哪里?
  • @MuratK.蓝牙服务在另一个类中广播 25 个整数。我使用整数来计算平均值,所以我知道它有效。我似乎无法让我的阵列工作......
  • 这就是填充的作用:用相同的值填充数组

标签: java arrays int


【解决方案1】:

只需阅读javadoc for fill()

将指定的 int 值分配给指定的 int 数组的每个元素。

您的代码获取 一个 int 值,然后使用一种方法将该值放入给定数组的每个槽中。

当您希望不同的值出现时:

  • 写一个循环
  • 在循环内:获取一个值并将其分配给“下一个”槽

喜欢:

int [] weightCount = new int[numElements];
for (int i = 0; i < numElements; i++) {
  weightCount[i] = intent.getExtras().getInt(BluetoothService.MESSAGE_WEIGHT_DATA); //take int values from bluetooth service
}

【讨论】:

  • 我的猜测,因为您最初的答案本质上是一个仅链接的答案,如果链接断开,则太模糊了。 (虽然它仍然有点模糊,没有明确说您指的是 Arrays.fill)我只是建议对此进行编辑。
  • 我不知道否决票与编辑的关系,但没有上下文的引用有时会让人很困惑。冗余通常会使清晰度更好。人们很快就会投反对票,所以如果最初的帖子足够好,可以独立存在,这会有所帮助。这只是我对原因的有根据的猜测。
【解决方案2】:

要添加一些东西到@GhostCat 答案,这是填充方法的代码:

/**
  * Assigns the specified int value to each element of the specified array
  * of ints.
  *
  * @param a the array to be filled
  * @param val the value to be stored in all elements of the array
  */
  public static void fill(int[] a, int val) {
        for (int i = 0, len = a.length; i < len; i++)
             a[i] = val;
  }

你用错了方法

【讨论】:

    猜你喜欢
    • 2016-01-27
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    相关资源
    最近更新 更多