0

このコードを実行しようとすると、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)

私はコーディングが初めてなので、これを修正することはできません。これを修正するのを手伝ってください。ありがとう

4

2 に答える 2

3

ArrayIndexOutOfBoundsException エラーは、配列の境界を超えていることを意味します。S+1あなたの場合、 st には S 列があり、 -th 要素 ( index )に到達しようとしました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] を更新します。これは意味がありません。

于 2013-07-05T15:12:01.190 に答える