LoginSignup
0
0

配列の基本

Last updated at Posted at 2024-04-14

配列の定義について

宣言
配列の変数名は複数形にしておくと分かりやすい。

//要素5個の配列
int[] scores = new int[5]; 

配列へ値の代入
添え字(インデックス)は0から始まる。

//例:5人の点数を代入する
int[] scores = new int[5];
scores[0] = 10;
scores[1] = 30;
scores[2] = 50;
scores[3] = 25;
scores[4] = 100;

配列の初期化
宣言と代入を同時に行う。
要素数を指定せずとも、勝手に箱を用意してくれる。

int[] scores = {10, 30, 50, 25, 100};

要素へのアクセス
配列名[取り出したいインデックス数] のように指定する。
インデックス数用の変数を指定すると、for文など動きがある場合に便利。

int[] scores = new int[2];
scores[0] = 10;
scores[1] = 30;
//取り出し
int score1 = scores[0];

// 応用
int index = 1;
System.out.println(scores[index]); // 30と出力

配列と拡張for文
score が実際に出力される変数。
scores配列に格納されたデータを、インデックス順にscoreという入れ物に入れる。
表示が終わったら次のデータを入れ直す。このscoreは一時的な入れ物のイメージ。

//順に10, 30, 50, 25, 100と出力
public class Lesson {
    public static void main(String[] args) {
        int[] scores = {10, 30, 50, 25, 100};
        for (int score : scores) {
            System.out.println(score);
        }
    }
}
0
0
0

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