問題
1から10までの和を求めるプログラムを作成せよ。
ただし、for文を用いること。
という問題を解いた際、以下のエラーが出ました。
Exception in thread "main" java.lang.Error: Unresolved compilation problems
私が書いた解答コードは以下です↓
public class java01 {
public static void main(String[] args) {
int n;
for (int i = 1; i <= 10; i++) {
n += i;
}
System.out.println(n);
}
}
原因は変数宣言時にnに値を代入していないことによるコンパイルエラーでした。
変数宣言時に初期化しないで変数を参照するとコンパイルエラーになると今回の問題で
学べることができました。
あざした!!!