gpt4 book ai didi

java - 最大和最小程序的数组索引越界异常

转载 作者:行者123 更新时间:2023-12-01 07:20:03 25 4
gpt4 key购买 nike

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

"Array index out of bound exception"

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);
}
}

最佳答案

不带{的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];
}
}

关于java - 最大和最小程序的数组索引越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41973393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com