3

別の配列からのデータから始まる配列を定義しようとしています。コードは、何千もの言葉よりも状況を説明します。

public class QualityCheck {



public QualityCheck (JTable table)
{
    //the data come from a JTable (that represents a school timetable)
    String [] dailyLessons= new String[table.getColumnCount()];
    String [] dailyClasses= new String[table.getColumnCount()];

    //checking all the days
    for (int i=1; i<table.getColumnCount(); i++)
    {
        //checking all the hours in a day
        for (int j=0; j<table.getRowCount(); j++)
        {
            //lesson is an array that contains the subject and the room in which the subject is erogated
            //lesson[0] contains the subject
            //lesson[1] contains the room
            String[] lesson = ((TabellaOrario.MyTableModel)table.getModel()).getLesson(j,i);

            //I'd like to put ALL the daily subjects in dailyLesson
            dailyLessons[j] = lesson[0];

            //I'd like to put All the daily rooms in dailyClasses
            dailyClasses[j] = lesson[1];

        }

        //trying if dailyLessons has the elements
        for (String s: dailyLessons)
        {
            System.out.println(s);
        }

    }   
}
}

このコードを実行すると、コンパイラは次のエラーで抗議します。

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 7

そして、それは文字列を証明します

dailyLessons[j] = lesson[0];

DailyLesson を定義するにはどうすればよいですか?

4

2 に答える 2

1

両方の配列を同じサイズに割り当ててから、両方に再度table.getColumnCount()インデックスjを使用すると、最大になります。table.getRowCount() - 1

おそらくそのうちの1つを size に割り当ててから、その1つだけのインデックスとしてtable.getRowCount()使用し、もう1つのインデックスとして使用する必要がありますが、決して使用しないのでわかりません。jidailyClasses

編集: どうやら、両方の配列に 1 つの列のデータを入力することを意図しているようです。次に、配列のサイズを行数に変更することで修正します。

// Changed table.getColumnCount() -> table.getRowCount()
String [] dailyLessons= new String[table.getRowCount()];
String [] dailyClasses= new String[table.getRowCount()];
于 2013-09-15T15:13:25.213 に答える
1

で配列を初期化し、table.getColumnCount()を使用してループしj < table.getRowCount()ます。

table.getColumnCount()それよりも小さい場合はtable.getRowCount()、AIOBE が得られます。

少なくとも配列を で初期化する必要がありますtable.getRowCount()

編集

dailyLessonsカプセル化とカプセル化を使用して小さなクラスを作成できますdailyClasses

class Lesson {
    public String dailyLesson;
    public String dailyClass;
}

そのクラスの配列を作成すると、毎日のレッスンとクラスの数が常に同じになります。

String [] lessons = new Lesson [table.getRowCount()];

後でループ内で:

lessons.dailyLesson = lesson[0];
lessons.dailyClass = lesson[1];

また、単純な配列の代わりにArrayListを使用することもできるため、配列のサイズを気にする必要はありません。

于 2013-09-15T15:13:47.983 に答える