0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Java 二次元配列

Last updated at Posted at 2020-11-29

#はじめに
学習用のメモになります。

#二次元配列とは?
二次元配列とは、2つのインデックスで要素を指定する配列のことです。

詳しくはこちら!
#サンプルコード

Main.java
public class Main {
    public static void main(String[] args) {
        String[][] teams = {{"勇者", "戦士", "魔法使い"}, {"盗賊", "忍者", "商人"}, {"スライム", "ドラゴン", "魔王"}};

        System.out.println(teams[0][0]);
         //実行結果 :勇者

        teams[0][0] = "剣士";
        // 勇者 → 剣士 に更新

        System.out.println(teams[0][0]);
        //実行結果:剣士


        System.out.println(teams.length);
        //実行結果:2
        //配列の長さ

        System.out.println(teams[0].length);
        //実行結果:3
        //teams[0]の配列の長さ

    }
}

二次元配列の宣言

Main.java
 String[][] teams = {{"勇者", "戦士", "魔法使い"}, {"盗賊", "忍者", "商人"}, {"スライム", "ドラゴン", "魔王"}};

二次元配列変数の宣言は、配列の型と次元がふたつあることを宣言する。変数の型の後に[]をふたつ書けば二次元配列になる。

#二次元配列をループ処理する

Main.java
// 2次元配列をループで処理する
public class Main {
    public static void main(String[] args) {
        String[][] teams = {{"勇者", "戦士", "魔法使い"}, {"盗賊", "忍者", "商人"}, {"スライム", "ドラゴン", "魔王"}};

        for (int i = 0; i < teams.length; i++) {
            for(int j = 0;  j < teams[i].length; j++) {
                System.out.print(teams[i][j] + " ");
            }
            System.out.println("");
            
        }
        //出力結果
        //勇者 戦士 魔法使い 
        //盗賊 忍者 商人 
        //スライム ドラゴン 魔王 
        

        //拡張forでのループ処理
        for (String[] team : teams) {
            for (String player : team) {
                System.out.print(player + " ");
            }
        }
    }
}

#二次元配列をnewで作成する

Main.java
// 2次元配列をnewで作成する

public class Main {
    public static void main(String[] args) {
        int[][] numberA = new int[3][4];
        for(int i =0;i<numberA.length; i++){
            for(int j =0;j<numberA[i].length;j++){
                numberA[i][j]=i*10+j;      //初期値を指定している
                System.out.print(numberA[i][j]+" ");  
                
            }
            System.out.println("");
            System.out.println("---");
        }
    }
}

出力結果

0 1 2 3 
---
10 11 12 13 
---
20 21 22 23 
---
0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?