25
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【ポケモン×Java】知識編 for文#2 〜for文を完全攻略!-配列編-~

Posted at

はじめに

for文の基本構文を覚えたら、次は配列と組み合わせてパワーアップ!
Javaでデータをまとめて扱うとき、配列とfor文はほぼセットで登場するよ。

この記事では、通常for文と拡張for文(for-each)の使い方や違い、配列を扱うときによくあるミスまで、ピカチュウと一緒に学んでいくよ!


🎓 配列とfor文の基本

配列は、同じ型のデータをまとめて管理する入れ物。

String[] pokemons = {"ピカチュウ", "フシギダネ", "ヒトカゲ", "ゼニガメ"};
for (int i = 0; i < pokemons.length; i++) {
    System.out.println(pokemons[i]);
}
  • pokemons.length は配列の要素数
  • 添字は0から始まり、最後は length - 1

🔄 拡張for文(for-each)

配列やコレクションを順番に処理するときに便利な簡易構文。

for (String name : pokemons) {
    System.out.println(name);
}
  • メリット: 添字を意識せずに全要素を処理できる
  • デメリット: 添字が必要な処理や、要素の直接更新には向かない

⚡ ピカチュウ例:技リストの表示

String[] moves = {"でんきショック", "スピードスター", "10まんボルト"};
for (String move : moves) {
    System.out.println("ピカチュウは " + move + " を使った!");
}

🐛 よくあるエラーパターン

  1. 境界値ミス
for (int i = 0; i <= pokemons.length; i++) { // NG: <= は範囲外アクセス
    System.out.println(pokemons[i]);
}

➡ 対策: i < pokemons.length にする

  1. 拡張forで更新できない
for (String move : moves) {
    move = move + "!"; // 配列の中身は変わらない
}

➡ 対策: 通常forで moves[i] = moves[i] + "!"; のように更新

  1. null要素の処理忘れ
String[] party = new String[3]; // 全要素null
for (String p : party) {
    System.out.println(p.length()); // NullPointerException
}

➡ 対策: nullチェックを入れる


🪄 次回予告

次はネストfor文!タイプ相性表の作成やチェック処理を通して、入れ子ループを攻略していくよ!

ピッピカチュウ!!


あとがき

ここまで読んでくれて、本当にありがとうございました。

「プログラミングって難しい…」って思ってた人も、
「ちょっと楽しいかも…!」って思ってもらえたらうれしいな。

次の投稿も、よろしくおねがいします。

💬 コメント・フィードバック歓迎!

「この章わかりやすかった!」
「これ表現まちがってない?」
「次は○○をやってほしい!」などなど、
お気軽にコメントで教えてくださいね!


25
8
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
25
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?