0

ここで助けが必要です。ユーザーが既にそこにあるインフラストラクチャのリストから正しい名前を付け、内部の値を使用する場合、ユーザーにインフラストラクチャを作成させようとしています。しかし、その後、このエラーが発生しました: Exception in thread "main" java.lang.NullPointerException TownObject は、インフラストラクチャが内部にある抽象クラスです。実行時のエラーの原因は何ですか? 前もって感謝します。

townObject commtowers = new infrastructure("telekom", "communication towers", 50);
townObject busstop = new infrastructure("litatrek", "bus stop", 30);

    townObject[][] ton = new townObject[20][20];

    String iname;

    System.out.println("Enter infrastructure name : ");            
    iname = sc.nextLine();
    sc.nextLine();

    for (int i=0; i < rows; i++){
        for (int j=0; j < columns; j++){
        ****if (iname.equalsIgnoreCase(ton[i][j].getName())
            {
                ton[x][y] = new infrastructure(infName, infType, infCost);
            }
            else
            {
                System.out.println("Infrastructure is not found.");
            }
        }
    }
4

1 に答える 1

0

ObjectsJavaのデフォルト値は ですnullObjectこれは、配列の要素にも適用されます。

配列ton自体はインスタンス化されますが、その個々の要素は依然として存在nullし、割り当てる必要があります。配列に対する操作を呼び出す前に、配列の要素をインスタンス化する必要があります。

for (int i=0; i < ton.length; i++) {
    for (int j=0; j < ton[i].length; j++) {
        ton[i][j] = new townObject();
        ton[i][j].setName(...);
    }
}
于 2013-05-12T20:57:27.313 に答える