我的代码有一点问题。 我尝试将代码从 python 重写为 java。
在 Python 中是:
data = bytearray(filesize)
f.readinto(data)
然后我尝试用java这样写:
try {
data = Files.readAllBytes(file.toPath());
} catch (IOException ex) {
Logger.getLogger(Encrypter.class.getName()).log(Level.SEVERE, null, ex);
}
for(int index : data) {
data[index] = (byte) ((byte) Math.pow(data[index], genfun((fileSize), index)) & 0xFF);
}
一切似乎对我来说都很好,但是当我编译它时,出现 java.lang.ArrayIndexOutOfBoundsException: -77
有人有线索或者可以更好地重写它吗?
最佳答案
这种形式的 for
循环(“增强型”for 循环)产生数组的值,而不是索引。值 -77
是 byte
的有符号值,而不是索引,因此出现异常。请注意,即使该值被提取为 byte
,Java 也非常乐意将 value
隐式扩展为您声明的 int
。
使用标准的for
循环:
for (int index = 0; index < data.length; index++)
{
byte value = data[index];
data[index] = (byte) ( /* Your byte manipulation of value goes here */ );
}
关于java - 数组索引越界异常 -77,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36584975/