配列のところからもう一回
Java再開です.
オブジェクト指向入門として,クラス宣言のお勉強の中で
public class Student { String name; //氏名 int[] tens; //試験の点数 public Student(String name, int x, int y, int z) { this.name = name; this.tens[0] = x; this.tens[1] = y; this.tens[2] = z; } public String toString(){ String s = "[" + name; for (int i = 0; i < tens.length; i++){ s += ", " + tens[i]; } s += "]"; return s; } public int total() { int sum = 0; for (int i = 0; i < tens.length; i++){ sum += tens[i]; } return sum; } }
ってクラス宣言してコンパイル→実行したら…
Exception in thread "main" java.lang.NullPointerException at Student.<init>(Student.java:6) at StudentTest.main(StudentTest.java:3)
っていうエラーが出たときメモ
(今日の日記は言葉が少ない…)
コンストラクタの中でint型の配列tensの要素に代入しているところの前で
配列の確保
this.tens = new int[3];
を忘れていました.
確かに
どこで配列の確保すればいいんだろう!??
と
書きながら,そわそわしてはいたのですが…><
あと,そのコンストラクタの中の
this.tens = new int[3]; this.tens[0] = x; this.tens[1] = y; this.tens[2] = z;
は,
このように各要素ごとに代入するしか記述方法はないのかなぁ
配列の初期化みたいな記述ができたらなぁ
と願ったところ
this.name = name; this.tens = new int[]{x,y,z};
でいけました.よかったです(o・ω・o)
明後日からはいよいよオブジェクト指向のお勉強です☆