プログラミングIII 第4回 配列 配列とは (p.176) 50人のテストの点数を変数に記憶させたい。 int test1=80: int test2=60; int test3=22; … int test50=35; test[0] test[1] test[2] test[3] … 配列の準備 配列変数testを準備 int[] test; test = new int[5]; int型の値を5つ記憶できる 配列要素を確保 様々な配列の宣言 (p.188) (その1) int[] test; test = new int[5]; (その2) int test[]; test= new int[5]; (その3) int test[] = new int[5]; 配列の利用 (p.183) int test[] = new int[3]; test[0]=80; test[1]=60; test[2]=22; for(int i=0; i<3; i++){ System.out.println((i+1)+”番目の人の点数は” +test[i]+”です。”); } 1番目の人の点数は80です。 2番目の人の点数は60です。 3番目の人の点数は22です。 配列の初期化 (p.190) int test[] = new int[3]; int[] test={80,60,22}; //test[0]=80; //test[1]=60; //test[2]=22; for(int i=0; i<3; i++){ System.out.println((i+1)+”番目の人の点数は” +test[i]+”です。”); } 配列変数 (p.193) int test[] ={80, 60, 22}; int test2[]; test2=test; for(int i=0; i<3; i++){ System.out.println(test2[i]); } 80 60 23 配列変数 (p.193) int test[] ={80, 60, 22}; int test2[]; test2=test; for(int i=0; i<3; i++){ System.out.println(test2[i]); } test[2]=100; System.out.println(test2[2]); 80 60 23 100 testという配列の別名として test2が設定されているだけ testの中を書き換えると test2の中も書き換わる 配列の応用 (p.199) 配列の長さ 配列変数名.length int test[] = {80, 60, 22}; System.out.println(test.length); 3 配列の応用 (p.) 配列のコピー int test[] = {80, 60, 22}; int test2[] = new int[3]; for (int i=0; i<test.length; i++) test2[i] = test[i] test[2]=100; System.out.println(test2[2]); 22 testの中を書き換えても test2の中は書き換わらない 配列のソート (p.202) int test[] = {22, 80, 57, 60, 50}; for (int s=0; s<test.length-1; s++){ for (int t=s+1; t<test.length; t++){ if(test[t] >test[s]){ int tmp=test[t]; test[t]=test[s]; test[s]=tmp; } } } for (int j=0; j<test.length; j++) System.out.println(test[j]); 80 60 57 50 22 バブルソート (p.204) 22 80 80 22 57 57 60 60 50 50 80 22 57 60 57 22 22 60 60 57 50 50 50 多次元配列 (p.205) int[][] test; test = new int[2][5]; 多次元配列の初期化 int[][] test={ {80, 60, 22, 50, 75},{90, 55, 68, 72, 58} } 各要素の数がそろっていなくてもOK int[][] test={ {80, 60, 22, 50}, {90, 55, 68, 72}, {33, 75, 63} }; for (int i=0; i<test.length; i++){ System.out.println(test[i].length); } 4 4 3
© Copyright 2024 ExpyDoc