【问题标题】:If statements in 2D arrays二维数组中的 if 语句
【发布时间】:2013-07-05 15:09:53
【问题描述】:

当我尝试运行此代码时,它显示 java.lang.ArrayIndexOutOfBoundsException 错误。请帮我修复此代码。

import java.util.*;

class Example {
public static void main(String args[]) {

    Scanner input = new Scanner(System.in);
    Random r = new Random();
    final int N, S;

    System.out.print("Input No of Students : ");
    N = input.nextInt();
    System.out.print("No of Subject : ");
    S = input.nextInt();

    int[][] st = new int[N][S];
    int[] stNo = new int[N];
    int[] stMax = new int[N];

    for (int i = 0; i < N; i++) {
        stNo[i] = r.nextInt(10000);
        for (int j = 0; j < S; j++) {
            st[i][j] = r.nextInt(101);
        }
    }

    // Find max Value of marks of a Student
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < S; j++) {
            if (st[i][j] > st[i][j + 1]) {
                stMax[i] = st[i][j + 1];
            }
        }
    }

    // Display marks
    // Dispaly Column names
    System.out.print("stNo\t");
    for (int i = 1; i < S + 1; i++) {
        System.out.print("Sub " + i + "\t");
    }
    System.out.print("Max");

    // Print Values
    for (int i = 0; i < N; i++) {
        System.out.print(stNo[i] + "\t");
        for (int j = 0; j < S; j++) {
            System.out.print(st[i][j] + "\t");
        }
        System.out.print(stMax[i]);
        System.out.println();
    }
}
}

错误是

  Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: (here shows the input for "S")
at pack1.Example.main(Example.java:31)

由于我是编码新手,因此无法解决此问题。请帮我解决这个问题。 谢谢

【问题讨论】:

  • 首先你需要学习如何识别错误的行。
  • 您应该在问题中包含整个堆栈跟踪(异常),并指出适用的行,因为我们无法通过仅查看代码立即看到行号。

标签: java arrays if-statement indexoutofboundsexception


【解决方案1】:

ArrayIndexOutOfBoundsException 错误意味着您超出了数组的边界。在您的情况下, st 有 S 列,您试图到达 S+1-th 元素(索引 S)。

st[i][j + 1] => 当j == S-1(循环结束)时,你做了一个越界。

现在,正如您的评论所说,您正在寻找最大值。那么代码应该是:

    stMax[i] = 0;
    for (int j = 0; j < S; j++) {
        if (st[i][j] > stMax[i]) {
            stMax[i] = st[i][j];
        }
    }

您的代码所做的是将当前值与下一个值进行比较。并且每次下一个值大于当前值时,您都会更新 stMax[i]。这没有意义。

【讨论】:

  • 非常感谢。这对我帮助很大。
【解决方案2】:

此行导致异常:

 stMax[i] = st[i][j + 1]; 

您将 j 迭代到数组的末尾,并且总是在寻找下一个元素。因此,当 j 到达数组的末尾时,它仍在寻找另一个索引,因此会出现 outOfBoundsException。

【讨论】:

    猜你喜欢
    • 2013-03-29
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    相关资源
    最近更新 更多