0
0

More than 1 year has passed since last update.

java アウトプット 繰り返し処理

Last updated at Posted at 2023-07-31

拡張for文を理解しよう

配列から要素を取り出すために、拡張for文を使ってみましょう。

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

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

コードを実行すると以下の通りになる。

1
5
10

拡張for文の使い方を理解しよう

拡張for文を使用する際の構文を確認しましょう。

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

この記述を行うと、以下のように動作します。

① 配列、あるいはArrayListから要素を1つ取り出す
② 取り出した要素を変数に代入する
③ {}内の処理を行う
④ 配列、あるいはArrayListの要素数分だけ処理を繰り返す

先ほど以下のようにコードを記述しましたが、変数scoresから要素を取り出し、ing型の変数scoreに代入するという動作になっています。

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