配列
- 配列は同じデータ型の変数を複数まとめて管理するもの
- 配列の生成には『new』を使う。生成時にデフォルト初期値が設定される。
※ 初期値:整数や少数なら0,文字なら空文字 ("") , 真偽値ならfalseが設定される
る
データ型[]配列名 = new データ型[要素数];
例)int[] score = new int[3];
score[0]= 80; //添字([]内の数字)は0から
- 配列の初期化
データ型[] 配列名 = {値1, 値2,・・・}
- 配列名.lengthで配列の要素数を取得できる
sample.java
public class Array01 {
public static void main(String[] args) {
int score[] = new int[3];
score[0] = 35;
score[1] = 64;
score[2] = 43;
String[]name = {"A","B","C"};
System.out.println(name[0]+"さん:" + score[0] + "点");
System.out.println(name[1]+"さん:" + score[1] + "点");
System.out.println(name[2]+"さん:" + score[2] + "点");
System.out.println("受験者数:" + score.length + "点");
}
}
多次元配列
- 配列の配列を作る
データ型[][] 配列変数名
例) int[][] num;
sample.java
public class Array02 {
public static void main(String[] args) {
int allScore[] = new int[2][3];
allScore[0][0] = 15;
allScore[0][1] = 34;
allScore[0][2] = 65;
allScore[0][3] = 95;
allScore[0][4] = 75;
//多次元配列の初期化
int[][] allScore ={{1,2,3},{4,5,6}};
System.out.println(allScore[0][0] + "点");
System.out.println(allScore[0][1] + "点");
System.out.println(allScore[0][2] + "点");
System.out.println(allScore[1][0] + "点");
System.out.println(allScore[1][1] + "点");
System.out.println(allScore[1][2] + "点");
System.out.println("allScore.length:" + allScore.length);
System.out.println("allScore[0].length:" + allScore[0].length);
}
}
参考サイト
配列の使い方やメモリ内の動きを理解しよう!多次元配列、コマンドラインからのデータ入力も解説【Java入門講座】2-4 配列