0
0

初期化について

Last updated at Posted at 2024-02-24

問題

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に値を代入していないことによるコンパイルエラーでした。
変数宣言時に初期化しないで変数を参照するとコンパイルエラーになると今回の問題で
学べることができました。
あざした!!!

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0