Java中用户自定义行列的二维byte数组创建问题求助
问题分析与修正方案
你的代码存在几个关键错误,导致无法正常运行,以下是逐一修正说明:
- 数组索引越界:循环条件使用
i<=n和j<=m,但Java数组索引从0开始,二维数组array的行数为n时,行索引范围是0~n-1,列索引范围是0~m-1,应改为i<n和j<m,否则会抛出ArrayIndexOutOfBoundsException异常。 nextBytes方法误用:Random.nextBytes()是用来批量填充整个byte数组的方法,返回值为void,不能赋值给单个元素array[i][j];且无需每次循环新建Random实例,复用初始化的rand对象即可。- 数组打印方式错误:直接打印
array只会输出对象内存地址,需要遍历数组才能显示具体元素值。
修正后的完整代码
import java.util.*; class Simple{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); Random rand = new Random(); System.out.println("enter the vertical and horizontal length of the matrix:"); int m = sc.nextInt(); int n = sc.nextInt(); // 对应输入的行数(vertical)和列数(horizontal)初始化二维数组 byte[][] array = new byte[m][n]; // 批量填充每一行的byte数组 for(int i=0; i<m; i++){ rand.nextBytes(array[i]); } // 遍历打印数组内容 System.out.println("生成的二维byte数组:"); for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ // 转成int方便查看byte的正负值(byte范围:-128~127) System.out.print((int)array[i][j] + " "); } System.out.println(); } sc.close(); } }
手动赋值的替代方案
如果不想用nextBytes批量填充,而是逐个生成随机byte值,可以替换内层循环为:
for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ // 生成-128~127之间的随机byte值 array[i][j] = (byte)rand.nextInt(256); } }
内容的提问来源于stack exchange,提问作者Nazar Chernigovskiy
相关产品推荐
相关产品推荐

