【问题标题】:how to cast int [] data type to byte [] data type如何将 int [] 数据类型转换为 byte [] 数据类型
【发布时间】:2016-06-25 16:34:28
【问题描述】:
I have the following error in compiler

return  ans;
                ^
  required: byte[]
  found:    int[]

我有这种方法,我想在其中返回一种字节。谁能告诉我如何转换 ans 以使其与我的方法类型兼容

public  byte[]  element(int m) {
    //if (q!= a.length)
    // throw new Exception("Array length does not equal k");
    int f;
    int q;
    int[] t;

    this.first = f;
    this.second = q;
    this.data = new int[q];

    for (int i = 0; i < t.length; ++i) {
        this.data[i] = t[i];
    }

    // if (!this.IsValid())
    //  throw new Exception("Bad value from array");


    int ans[] = new int[this.second];

    int a = this.first;
    int b = this.second;
    int x = (choose(this.first,this.second) - 1) - m; // x is the "dual" of m

    for (int i = 0; i < this.second; ++i) {
        ans[i] = largestV(a, b, x); // largest value v, where v < a and vCb < x
        x = x - choose(ans[i], b);
        a = ans[i];
        b = b - 1;
    }

    for (int i = 0; i < this.second; ++i) { 
        ans[i] = (first-1) - ans[i];
        return  ans;
    }
}

注意:我希望它返回字节类型而不是 int,但我正在尝试转换 ans 但没有成功。

【问题讨论】:

  • 如果你想要一个字节[],为什么要将它创建为一个int[]?只需将其创建为一个字节,然后在赋值“ans[i] = (byte) maximumV(...)”中进行转换。

标签: java arrays casting


【解决方案1】:

您必须将 int[] ans 更改为 Byte[] ans,您试图返回一个 int 数组,但您必须返回您的字节数组

int f;
   int q;
  int [] t;

    this.first = f;
    this.second = q;
    this.data = new int[q];
    for (int i = 0; i < t.length; ++i)
      this.data[i] = t[i];

   // if (!this.IsValid())
    //  throw new Exception("Bad value from array");


        byte ans []= new byte[this.second];

        int a = this.first;
        int b = this.second;
        int x = (choose(this.first,this.second) - 1) - m; // x is the "dual" of m

        for (int i = 0; i < this.second; ++i) {
            ans[i]= largestV(a, b, x); // largest value v, where v < a and vCb < x
            x = x - choose(ans[i], b);
            a = ans[i];
            b = b - 1;
        }

        for (int i = 0; i < this.second; ++i)

            ans[i] = (first-1) - ans[i];

        return  ans;
    }

【讨论】:

  • 我在发布我的问题之前尝试过,但由于 byte ans []= new byte[this.second]; 下面的所有代码都无法正常工作然后必须转换为字节
  • @johnsmit 那么这就是你必须做的。您可以将int 转换为byte,但不能将int[] 转换为byte[]。
【解决方案2】:

不知道你为什么要在int 上工作并返回byte。除了数据,您可以创建一个与ans 大小相同的新字节数组,并在最后一个循环中执行此操作

for (int i = 0; i < this.second; ++i)
{ 
    ans[i] = (first-1) - ans[i]);
    ans_byte_version[i] =  (byte) ((first-1) - ans[i]);
}
return ans_byte_version;

但是,如果您告诉我们您要做什么会更好。为什么一开始就需要字节时却声明了 int。

【讨论】:

    猜你喜欢
    • 2020-10-22
    • 2014-02-20
    • 2020-06-24
    • 1970-01-01
    • 2013-08-19
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    相关资源
    最近更新 更多