LoginSignup
0
0

More than 3 years have passed since last update.

Java 繰り返しの処理

Last updated at Posted at 2020-11-27

はじめに

学習用のメモになります。

while文

// whileによるループ処理

public class Main {
    public static void main(String[] args) {
        // カウンタ変数の初期化
        while (条件式) {
            // 繰り返し処理
            // カウンタ変数の更新
        }
    }
}
  • 括弧の中に入るのは条件式のみ

iが5以下の場合の繰り返す処理

// whileによるループ処理

public class Main {
    public static void main(String[] args) {
        int i = 0;    // カウンタ変数の初期化
        while (i <= 5) {    // 0 -> 1 -> 2 -> 3 ・・・ 5 -> 6
            System.out.println("hello world " + i);    // 繰り返し処理
            i = i + 1;    // カウンタ変数の更新
        }
        System.out.println("last " + i);
    }
}

出力結果

hello world 0
hello world 1
hello world 2
hello world 3
hello world 4
hello world 5

for文

// forによるループ処理

public class Main {
    public static void main(String[] args) {
        for(カウンタ変数の初期化; 条件式; カウンタ変数の更新) {
             // 繰り返し処理
        }
    }
}
  • 括弧の中には初期化式、条件式、変化式
  • i のスコープは for 文の中だけ
  • i をスコープ外にまたがって使用する場合、
  • スコープの外で宣言しておく必要がある
  • 実は処理が一行だけなら中括弧はなくても動く
  • 変化式が実行されるのは処理が行われたあと
  • list 等の中身を全て参照する場合などには for-each 文が使える
*スコープとは

プログラム中で定義された変数や定数、関数などを参照・利用できる有効範囲を表します

iが4以下だったら処理を繰り返す処理

// forによるループ処理

public class Main {
    public static void main(String[] args) {
        for(int i=0; i<=4; i++) {
             System.out.println(i);
        }
    }
}

配列の繰り返し処理

// ループで配列を操作する

public class Main {
    public static void main(String[] args) {
        String[] team = {"勇者", "戦士", "魔法使い"};
        System.out.println(team.length);

        for(int i=0;i<team.length; i++){
            System.out.println(team[i]);
        }
    }
}

出力結果

3
勇者
戦士
魔法使い

拡張for文の繰り返し処理

String[] team = {"勇者", "戦士", "魔法使い", "忍者"};
for (String member : team) {
    System.out.println(member);
}

出力結果

勇者
戦士
魔法使い

for文とwhile文の使い分け

  • 単純な前処理、単純な後処理が必要な反復処理においては for 文
    • 例えば: 繰り返す回数が分かっている処理など
  • 複雑な前処理や後処理が必要な反復処理が必要な場合は while 文を使う
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