0
0

Java学習 繰り返し処理 拡張for文

Last updated at Posted at 2024-01-19

繰り返し処理の種類

javaでは繰り返し処理を行うとき下記の2種類がある。

  • for文
  • 拡張for文

拡張for文は、Rubyでのeachメソッドに似た機能を持っている。
Rubyのeachメソッドとは書き方が異なるが、使い方は似ている。

拡張for文

拡張for文を実行

配列から要素を取り出す

class Main {
  public static void main(String[] args) {
    int[] scores = {1, 2, 3, 4, 5};

    for(int score : scores) {
      System.out.println(score);  
    }
  }
}

実行結果

1
2
3
4
5

ArrayListから要素を取り出す場合

ArrayListから要素を取り出す場合も使い方は同じ。

import java.util.ArrayList;

class Main {
  public static void main(String[] args) {
    ArrayList<Integer> scores = new ArrayList<Integer>();

    scores.add(2);
    scores.add(3);
    scores.add(5);
    scores.add(7);
    scores.add(11);
    scores.add(13);

    for(int score : scores) {
      System.out.println(score);  
    }
  }
}

実行結果

2
3
5
7
11
13

拡張for文の使い方

拡張for文の構文

for ( 要素を格納する変数を宣言  :  配列あるいはArrayListの変数名) {
  取り出した要素を使用して行う処理を記述
}

この記述を行うと、以下のような流れで動作する。

  1. 配列、もしくはArrayListから要素を1つ取り出す。
  2. 取り出した要素を変数に代入する。
  3. {}内の処理を行う。
  4. 配列、もしくはArrayListの要素数分だけ処理を繰り返す。
for(int score : scores) {
  System.out.println(score);  
}

上記のようなコードは、変数scoresから要素を取り出し、int型の変数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