1
1

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 5 years have passed since last update.

Java,二次元配列について

Posted at

はじめに

Javaの二次元配列について理解を深めたいと思い、まとめました。

##サンプルコード

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

Main.java

public class Main {
    public static void main(String[] args) throws Exception {
        
        //配列の作成方法 - ⑴ ※ 解説
        
        //String[][] teams;
        
        //teams = new String[2][3];
        
        //配列変数の宣言
        //new演算子で要素数を指定し、teams へ代入
        
        //配列の作成方法 - ⑵
      
        //String[][] teams = new String[2][3];
        
        //⑴の方法を 同時に行う

        //teams[0][0] = "勇者";
        //teams[0][1] = "戦士";
        //teams[0][2] = "魔法使い";
        //teams[1][0] = "盗賊";
        //teams[1][1] = "忍者";
        //teams[1][2] = "商人";
        
        //配列へ格納
        
        //配列の作成方法 - ⑶
        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
teams = new String[n][m];

// n:配列の要素数 , m:要素に格納された配列の要素数

座標で言うなら y座標はn, x座標はmとなる。
参考までにここをクリック!

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?