关于数组的一段代码

1 篇文章 0 订阅
1 篇文章 0 订阅

程序实现了自定义数组(多少行,多少列),并输出数组。

代码如下:

import java.util.Scanner;

class q {
    public static void main(String[] args) {
        // 确定数组
        int x = 0, y = 0, z = 0, i = 0;
        Scanner input = new Scanner(System.in);
        System.out.println("h = ?");
        z = input.nextInt();
        System.out.println("s = ?");
        i = input.nextInt();
        z = z + 1;
        int a[][] = new int[i][z];
        // 输出数组样式
        System.out.println("");
        System.out.println("赋值前的数组");
        System.out.println("");
        for (x = 0; x < i; x++) {
            for (y = 0; y < z; y++) {
                System.out.print("a[" + x + "][" + y + "]" + " ");
            }
            System.out.println("");
        }
        // 输入数组的值
        System.out.println("");
        System.out.println("请给数组赋值");
        System.out.println("");
        for (x = 0; x < i; x++) {
            for (y = 0; y < z; y++) {
                System.out.println("a[" + x + "][" + y + "]" + " = ?");
                a[x][y] = input.nextInt();

            }
        }
        System.out.println("");
        System.out.println("赋值后的数组");
        System.out.println("");
        // 输出赋值后的数组
        for (x = 0; x < i; x++) {
            for (y = 0; y < z; y++) {
                System.out.print(a[x][y] + " ");
            }
            System.out.println("");
        }
    }
}

=======================

说明:再编写这段代码的时候,遇到了数组下标溢出的问题。纠结半天,原来是赋值以后,z控制的长度大于数组的值得长度,造成的。Java初学者一定要注意这一点奥。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值