数组索引超出最大和最小程序的异常

时间:2017-02-01 06:37:49

标签: java bluej

我正在制作一个程序来接受二维数组中的数字并找到最大和最小的数字。 但是当我输入mu输入时,它会在第二个if语句中显示错误:

  

"数组索引超出绑定异常"

import java.util.Scanner;
public class DDA_MaxMin
{
    public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);
        int ar[][] = new int[4][4];
        int a,b,c=0,d=0;
        for(a=0;a<4;a++)
        {
            for(b=0;b<4;b++)
            {
                System.out.println("Enter the numbers in the matrix "+a+" "+b);
                ar[a][b]=in.nextInt();
            }
        }
        c=ar[0][0];
        d=ar[0][0];
        for(a=0;a<4;a++)
        {
            for(b=0;b<4;b++)
            if(c>ar[a][b])
            c=ar[a][b];
            if(d<ar[a][b])         
            d=ar[a][b];
        }
        System.out.println("The greatest number is "+d);
        System.out.println("The smallest number is "+c);
    }
}

4 个答案:

答案 0 :(得分:4)

没有{的for循环仅对下一行或下一个语句有效。

for(b = 0; b < 4; b++)
 if(c>ar[a][b])
    c=ar[a][b]

b值为4

并且之后的if语句超出for循环因此超出范围异常。

将它们括在大括号中。

for(a=0;a<4;a++)
    {
        for(b=0;b<4;b++){
        if(c>ar[a][b])
        c=ar[a][b];
        if(d<ar[a][b])         
        d=ar[a][b];
        }
    }

答案 1 :(得分:1)

嘿,你错过了第二个花括号,因为正确的代码将是

答案 2 :(得分:1)

问题在于您的第二个for循环处理变量b。它缺少大括号。将其更改为:

for(a=0;a<4;a++) {
    for(b=0;b<4;b++) {
        if(c>ar[a][b])
            c=ar[a][b];
        if(d<ar[a][b])         
            d=ar[a][b];
    }
}

答案 3 :(得分:1)

`

public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);
        int ar[][] = new int[4][4];
        int a,b,c=0,d=0;
        for(a=0;a<4;a++)
        {
            for(b=0;b<4;b++)
            {
                System.out.println("Enter the numbers in the matrix "+a+" "+b);
                ar[a][b]=in.nextInt();
            }
        }
        c=ar[0][0];
        d=ar[0][0];
        for(a=0;a<4;a++)
        {
            for(b=0;b<4;b++)
            {
             if(c>ar[a][b])
               c=ar[a][b];
             if(d<ar[a][b])         
               d=ar[a][b];
                 }
        }
        System.out.println("The greatest number is "+d);
        System.out.println("The smallest number is "+c);
    }`

你在for循环中缺少括号,你试图找到最大和最小的整数。

相关问题